2012-02-02 117 views
1
SubCollection extends Backbone.Collection 

Model extends Backbone.Model 
    subcollection: new SubCollection() 

model1 = new Model 

model2 = new Model 

model1中的集合更改时,我需要更新model2中的集合。他们不能作为同一个集合的参考,当我需要对变化作出反应并将其应用于其他模型中的集合时。对模型中的集合中的事件做出反应?

我该怎么做?这很难吗?

谢谢!

+0

我想知道这一点。有没有一些标准的方式或公认的惯例,将各种事件通过层次结构展开并听取/捕捉它们? – leeoniya 2012-02-02 23:02:10

回答

1

好,

我们不能真正确保只有在模型1和模型2,我们可以有一个model3和model4,所以我们不能真的去手动绑定到款,否则你会得到一个大搞成这个样子:

// not an option... >> huge mess :) 
model1.bind('add', myFunction()); 
model2.bind('add', myFunction()); 
model3.bind('add', myFunction()); 

所以,我们能做些什么,而不是

将实现我们的应用程序的事件聚合。并改为使用自定义事件。

// application object 
var app = { 
    evt: _.extend({}, Backbone.Events); 
}; 

// subcollection 
var SubCollection = Backbone.Collection.extend({ 
    initialize: function(){ 

     _.bindAll(this, "bubbleEvent", "catchBubbledEvent"); 

     this.bind('reset', this.myBubble); 
     this.bind('add', this.myBubble); 
     this.bind('reset', this.myBubble); 
     //... every event you want to catch 

     app.evt.bind('myCustomEvent', this.catchBubbledEvent); 
    }, 

    bubbleEvent: function(x, y){ 
     // triggering a general event, passing the parameters 
     app.evt.trigger('myCustomEvent', x, y, this); 
    }, 

    catchBubbledEvent: function(x, y, originalCollection) { 
     // catch any event raised on the event aggregator and cancel out the loop (don't catch events raised by this very own collection :) 
     if(originalCollection.id === this.id) 
      return; 

     // do your stuff here ... 
    } 
}); 

//model 
var myModel = Backbone.Model.extend({ 
    // notice me setting a unique ID in the collection, i pass in the client id of this instance of the model 
    subCollection: new SubCollection({id: this.cid}); 
}); 

所以基本上我们赶上我们要收集的每一个事件,然后我们通过它波谷与对单一事件的一般事件聚集,我们有我们的整个应用程序,什么都可以绑定到这一点,做的东西当适当的事件发生时,我们的集合也可以绑定到它上面,并做些事情。因为您的收藏可能会捕获它自己发出的事件,所以我们需要一个小型测试来消除这些情况......并且只有在另一个收藏引发此事件时才会继续。

相关问题