当通过轮询端点更新模型时,我在触发更改事件时遇到了一些麻烦。我非常确定这是因为集合实际上没有更新。我正在使用Backbone 0.9.9中的新选项(update: true
),它试图智能地更新集合,而不是完全重置集合。
当我在updateClientCollection
函数的末尾插入console.log(this)
时,当通过setInterval
调用updateClientCollection
时,this.clientCollection
似乎没有更新。但是,我确实看到终结点正在被轮询,并且终结点正在为客户端返回新的不同值。
managementApp.ClientListView = Backbone.View.extend({
className: 'management-client-list',
template: _.template( $('#client-list-template').text() ),
initialize: function() {
_.bindAll( this );
this.jobId = this.options.jobId
//the view owns the client collection because there are many client lists on a page
this.clientCollection = new GH.Models.ClientStatusCollection();
this.clientCollection.on( 'reset', this.addAllClients );
//using the initial reset event to trigger this view's rendering
this.clientCollection.fetch({
data: {'job': this.jobId}
});
//start polling client status endpoint every 60s
this.intervalId = setInterval( this.updateClientCollection.bind(this), 60000 );
},
updateClientCollection: function() {
//don't want to fire a reset as we don't need new view, just to rerender
//with updated info
this.clientCollection.fetch({
data: {'job': this.jobId},
update: true,
reset: false
});
},
render: function() {
this.$el.html( this.template() );
return this;
},
addOneClient: function( client ) {
var view = new managementApp.ClientView({model: client});
this.$el.find( 'ul.client-list' ).append( view.render().el );
},
addAllClients: function() {
if (this.clientCollection.length === 0) {
this.$el.find( 'ul.client-list' ).append( 'No clients registered' );
return;
}
this.$el.find( 'ul.client-list' ).empty();
this.clientCollection.each( this.addOneClient, this );
}
});
managementApp.ClientView = Backbone.View.extend({
tagName: 'li',
className: 'management-client-item',
template: _.template( $('#client-item-template').text() ),
initialize: function() {
_.bindAll( this );
this.model.on( 'change', this.render );
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
return this;
}
});
1条答案
按热度按时间h79rfbju1#
根据我从代码中收集到的信息,您只绑定了集合的
reset
事件。根据文档,当您将
{ update: true }
作为提取选项的一部分传递时,Backbone.Collection
在提取后使用.update()
方法。Backbone.Collection.update()
为每个模型触发相关的add
、change
和remove
事件。您还需要绑定到这些事件,并执行相关函数来更新UI。在您的情况下,您可以将现有的
addOneClient
方法系结至集合上的add
事件。在你的
ClientView
类中,你可以绑定到change
和remove
事件来分别重新呈现和移除视图。记住使用listenTo()
,这样当ClientView
对象是remove()
本身时,它就可以轻松地清除事件。