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

Model extends Backbone.Model 
    subcollection: new SubCollection() 

model1 = new Model 

model2 = new Model 

model1의 컬렉션을 변경하면 model2의 컬렉션을 업데이트해야합니다. 그들은 동일한 컬렉션에 대한 참조가 될 수 없습니다. 하나가 변경되면 변경에 반응하고 다른 모델의 컬렉션에 적용해야합니다.모델 내의 컬렉션에있는 이벤트에 반응합니까?

어떻게하면됩니까? 이 일을하기가 어렵습니까?

감사합니다. 잘

+0

나는 이것을 알고 싶습니다. 계층 구조를 통해 다양한 이벤트를 버블 링하고이를 수신/수신하기위한 표준 방식 또는 수락 된 규칙이 있습니까? – leeoniya

답변

1

,

우리가 정말 그렇지 않으면 당신은 얻을 것입니다, 우리는 model3 및 model4을 가질 수있다, 그래서 우리는 실제로 모델에 수동으로 바인딩 갈 수 없어 단지 모델 1과 모델 2가 확신 할 수없는 이 같은 큰 혼란 :

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

그래서, 우리가 대신 할 수있는

우리의 응용 프로그램에서 이벤트 애그리 게이터 (aggregator)를 구현하는 것입니다. 대신 사용자 정의 이벤트로 작업하십시오.

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

그래서 기본적으로 우리는 우리가 원하는 컬렉션의 모든 이벤트를 잡을, 우리는 그리 게이터 우리가 우리의 전체 앱이 무엇이든 그 바인딩 할 수는 단일 이벤트에 대한 일반적인 이벤트에 여물 통과, 물건을 적절한 사건이 제기 될 때, 우리의 소장품도 그것에 묶여서 할 수 있습니다. 컬렉션이 자신이 보낸 이벤트를 포착하는 것이 가능하기 때문에 이러한 상황을 취소하기위한 작은 테스트가 필요하며 다른 컬렉션에서이 이벤트가 발생했을 때만 계속 진행됩니다.

관련 문제