0

当通过端点轮询更新模型时,我在触发更改事件时遇到了一些麻烦。我很确定这是因为该集合实际上并未更新。我正在使用 Backbone 0.9.9 中的新选项( update: true),它试图智能地更新集合,而不是完全重置它。

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

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;
  }
});
4

1 回答 1

0

从我可以从您的代码中收集到的信息来看,您仅对reset集合事件具有约束力。

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

Backbone.Collection.update()为每个模型触发相关add的 ,change和事件。remove您还需要绑定到这些并执行相关功能来更新您的 UI。

在您的情况下,您可以将现有addOneClient方法绑定到add集合上的事件。

在您的ClientView课程中,您可以绑定到changeremove事件以分别重新渲染和删除视图。请记住使用listenTo(),以便对象在它本身ClientView时可以轻松地清理事件。remove()

于 2012-12-20T02:18:02.280 回答