我试图更新表视图中的一些列时,一个计时器触发的收集我得到一个子集的(只改变)属性。尝试了各种代码从谷歌,但没有运气。
希望仅更新视图中名称和指定之外的年龄属性,而不是重新渲染整个视图。
这是我代码
<div class='mainBody'>
<table class="table">
<tr class="success">
<td>Name</td>
<td>Age</td>
<td>Ocupation</td>
</tr>
</table>
</div>
<script id="externalViewTemplate" type="text/template">
<td width='25%'> <%= name %> </td>
<td width='25%' id="age"> <%= age %> </td>
<td width='25%'> <%= occupation %> </td>
</script>
脚本:
//Person Model
var PersonModel = Backbone.Model.extend({
_id:"id"
});
//Person collection - People
var PeopleCollection = Backbone.Collection.extend({
model: PersonModel,
view: PeopleView,
initialize: function(){
this.updateAge = setInterval(this.getAge.bind(this), 3000);
},
getAge: function()
{
var per = [{
id:1,
age: 31
},
{
id:2,
age: 32
},
{
id:3,
age: 37
}];
this.reset(per);
}
});
//Person view - Responsible for rendering one person
var PersonView = Backbone.View.extend({
tagName: 'tr',
template: _.template( $('#externalViewTemplate').html() ),
initialize: function() {
this.model.on("change:age", this.update, this);
},
update: function() {
this.el.cells["age"].innerHTML = this.model.get("age");
},
render: function(){
this.$el.append(this.template(this.model.toJSON()));
//console.log(this.$el.find('.edit'));
return this;
}
});
//person view collection - rendering the rows collection
var PeopleView = Backbone.View.extend({
view: PersonView,
initialize: function(options){
this.collection = options.collection,
this.collection.on("reset", this.update, this);
},
render: function(){
this.collection.each(function(person){
var personRow = new PersonView({model: person});
this.$el.append(personRow.render().el);
}, this);
},
update: function(){
this.collection.each(function(person){
//var personRow = new PersonView({model: person});
this.model.age = person.age;
}, this);
}
});
//Try this code
var personCollection = new PeopleCollection([
{
id:1,
name: 'Raju',
age: 31,
occupation: 'Dotnet Programmer'
},
{
id:2,
name: 'Rajesh',
age: 32,
occupation: 'Developer'
},
{
id:3,
name: 'Ramesh',
age: 33,
occupation: 'Designer'
}
]
);
var peopleList = new PeopleView({ el: '.table', collection: personCollection});
peopleList.render();
希望仅更新视图中名称和指定之外的年龄属性,而不是重新渲染整个视图。
1条答案
按热度按时间zpqajqem1#
根据
<tr> - MDN
的cells
属性返回一个HTMLCollection
.你的更新单元格的代码应该是由于您很可能拥有jQuery和 Backbone.js ,因此您可以只执行以下操作
请注意,我使用
className
“age”是因为您不应该在模板中使用id
,这样会出现重复。