轮询api时,不会更新骨干集合

时间:2012-12-19 22:46:34

标签: javascript-events backbone.js backbone-collections

通过轮询端点更新模型时,我遇到一些麻烦。我很确定这是因为该集合实际上并未更新。我在Backbone 0.9.9中使用new optionupdate: true)尝试智能地更新集合而不是完全重置它。

当我在console.log(this)功能的末尾插入updateClientCollection时,this.clientCollection通过updateClientCollection调用setInterval时似乎没有更新。但是,我确实看到端点正在被轮询,端点正在为客户端返回新的和不同的值。

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 个答案:

答案 0 :(得分:0)

根据我从代码中收集的内容,您只对该集合的reset事件具有约束力。

根据文档,Backbone.Collection在您提取.update()作为获取选项的一部分时,在获取后使用{ update: true }方法。

Backbone.Collection.update()会针对每个模型触发相关的addchangeremove事件。您还需要绑定到这些并执行相关功能来更新UI。

在您的情况下,您可以将现有的addOneClient方法绑定到收藏中的add事件。

ClientView类中,您可以绑定到changeremove事件,分别重新渲染和删除视图。请务必使用listenTo(),以便ClientView对象可以轻松清除事件remove()本身。