2012-02-02 121 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}); 
}); 

所以基本上我們趕上我們要收集的每一個事件,然後我們通過它波谷與對單一事件的一般事件聚集,我們有我們的整個應用程序,什麼都可以綁定到這一點,做的東西當適當的事件發生時,我們的集合也可以綁定到它上面,並做些事情。因爲您的收藏可能會捕獲它自己發出的事件,所以我們需要一個小型測試來消除這些情況......並且只有在另一個收藏引發此事件時纔會繼續。

相關問題