2012-05-28 34 views
1

再次出現一些主幹問題。代替長描述的是一些示例代碼:主幹和延遲破壞事件

var Group = Backbone.Model.extend({ 

    defaults: { 
     Product: new Products() 
    }, 

    initialize: function(data){ 
     var _this = this; 

     var products = new Products(data.Product); 
     this.set('Product', products); 

     this.get('Product').each(function(product){ 
      product.on('destroy', function(){ 
       _this.trigger('change'); 
      }, _this); 
     }); 

     this.bind('change', this.update, this); 
    }, 

    update: function(){ 
     console.info("something changed"); 

     console.log(this.get('Product').toJSON()); 
    }, 

}); 

所以組模型包含Product-collection,它明顯包含產品。在初始化時,我試圖確保當產品被更改和銷燬時,組的更新方法被稱爲示例。所有似乎都很好地工作,事件被調用,屬性看起來不錯,但當我在產品模型中調用銷燬方法時,它失敗。在更新中,我嘗試打印產品集合的內容,並且在移除完成之前得到的是產品。如果我在500ms超時後調用此調試行,則內容正常。產品被刪除等

所以根據我的理解,產品的銷燬事件被調用,然後傳遞到組實際從集合中刪除之前完成。我究竟做錯了什麼?

回答

1

主幹通過監聽模型上的destroy事件來處理集合中已銷燬模型的移除:請參閱源代碼Backbone.Model - destroyBackbone.Collection - _onModelEvent

無法保證處理程序執行的順序,您將不得不使用其他方法。例如,聽destroy事件的收集將火後的模型實際刪除:

initialize: function(data){ 
    var _this = this; 

    var products = new Products(data.Product); 
    this.set('Product', products); 

    this.get('Product').on("destroy", this.update, this); 
    this.bind('change', this.update, this); 
}, 

檢查這個小提琴http://jsfiddle.net/NUtmt/一個完整的例子。

+0

這是有效的。謝謝! – jaylinen