2012-11-29 92 views
2

在我的應用程序中,我有兩個視圖共享相同模型的情況。從集合中刪除模型將刪除視圖的參考

我在通過模型訪問集合並從集合中刪除模型時遇到了問題。問題是在調用this.model.collection.remove(this.model)後,視圖的參考this.model未定義。

我不是在刪除事件前解除綁定的原因是,我需要mySecondView才能知道刪除事件,以便從DOM中刪除它。

MyView = Backbone.View.extend({ 

    events : { 
     'click .delete' : deleteModel 
    } 

    initialize : function() { 

     this.model.on('remove', this.dispose, this) 
    }, 


    deleteModel : function() { 

     if(this.model.isNew()) 
     { 

      this.model.collection.remove(this.model); 

      //remove all the events bound to the model 
      this.model.unbind(); //this.model is undefined 

      this.dispose(); 
     } 

    } 
}); 


MySecondView = Backbone.View.extend({ 

    initialize : function() { 

     //call the custom dispose method to remove the view 
     this.model.on('remove', this.dispose, this); 
    } 

}); 

myModel  = new Backbone.Model();  
myCollection = new Backbone.Collection(myModel); 

myView  = new MyView({ model : myModel }); 
mySecondView = new MySecondView({ model : myModel }); 

唯一可行的方法是通過創建一個局部變量參考模型deleteModel

有什麼建議?

+0

當你[銷燬](http://documentcloud.github.com/backbone/#Model-destroy)一個模型時,它會觸發一個'destroy'事件,該事件冒泡到集合中,所以你不需要調用' this.model.collection.remove(this.model);' – Jack

+0

這是一個新的模型,它不存在於服務器上,只需要在客戶端刪除。我有一個打字錯誤,我修正了我調用'this.destroy'而不是'this.dispose'的地方。 – Daniel

回答

0

問題是編程錯誤。

當調用this.model.collection.remove(this.model);時,在綁定到dispose方法的模型上調用remove事件,該方法刪除了對模型的任何本地引用。因此對模型的引用丟失了。