2013-02-18 42 views
2

模型銷燬時,模型集合不會發出「同步」事件。文檔seems to say the opposite。這裏是我的代碼片段:模型銷燬時不會發出同步事件 - Backbonejs

var MyModel = Backbone.Model.extend({ id: 1, val: "foo" }); 
var MyCollection = Backbone.Collection.extend({ model: MyModel, url: '/api/models' }); 

var myCollection = new MyCollection(); 

myCollection.on('sync', function() { console.log('synced!'); }); 
myCollection.on('remove', function() { console.log('removed!'); }); 

myCollection.fetch(); // => outputs synced! 

    // .. wait for collection to load 

myCollection.at(0).destroy(); // => outputs removed! but *NOT* synced!   

如果我沒理解好,醫生說的「破壞」事件應該冒泡的收集和發出「同步」事件。上面代碼中的集合是否應該發出「同步」事件?

回答

6

「同步」事件。這就是爲什麼收集不會觸發「同步」事件。儘管如此,這個收藏會傳遞'毀滅'事件。

4

編輯:即使使用wait:true選項,在從集合中刪除「模式」時,模型上會觸發「同步」。

這是Backbone的代碼,它觸發集合上的模型事件。因爲該模型不會觸發「同步」事件(然後觸發集合)由於在同步過程中的錯誤

// Internal method called every time a model in the set fires an event. 
// Sets need to update their indexes when models change ids. All other 
// events simply proxy through. "add" and "remove" events that originate 
// in other collections are ignored. 
_onModelEvent: function(event, model, collection, options) { 
    if ((event === 'add' || event === 'remove') && collection !== this) return; 
    if (event === 'destroy') this.remove(model, options); 
    if (model && event === 'change:' + model.idAttribute) { 
    delete this._byId[model.previous(model.idAttribute)]; 
    if (model.id != null) this._byId[model.id] = model; 
    } 
    this.trigger.apply(this, arguments); 
}, 

你的問題是最有可能。

從骨幹源,你可以看到'sync'在請求成功時觸發,所以也許你可以調試它,看看sync中的成功回調是否被命中?

var success = options.success; 
    options.success = function(resp) { 
     if (success) success(model, resp, options); 
     model.trigger('sync', model, resp, options); // breakpoint here. 
    }; 

你可以把一個斷點,在那裏,看看是否該事件被觸發?我認爲它不會擊中這條線。

同時嘗試使用一個錯誤回調:從集合中刪除後觸發銷燬的對象上

myCollection.at(0).destroy({ 
    error: function(model, xhr, options){ 
     console.log(model); // this will probably get hit 
    } 
}); 
+0

在上面的代碼中,我正在監聽集合上的同步,而不是模型:它不會被觸發。刪除事件IS觸發。我的問題不是關於那些事件。這是關於同步事件沒有被收集觸發。請閱讀我的代碼和問題。 – nakhli 2013-02-18 18:59:15

+0

我讀過了。當在模型上觸發'sync'時,集合中的_onModelEvent觸發集合上的相同事件。把我建議的斷點放在一起,看看它是否被擊中,你可能會在同步中出現錯誤,這會導致你的問題。 – 2013-02-18 19:01:25

+0

當你銷燬一個模型時,除非你傳遞'wait:true',否則樂觀地將它從集合中移除。這就是爲什麼你會得到'刪除'事件,而不是'同步'事件。同步不成功。 – 2013-02-18 19:05:25