3

モデルが破棄されたときに、モデルコレクションが「sync」イベントを発行していません。ドキュメントには反対のことが書かれているようです。これが私のコードスニペットです:

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!        

私がよく理解している場合、ドキュメントには、「破棄」イベントがコレクションにバブルアップして「同期」イベントを発行する必要があると書かれています。上記のコードのコレクションは「sync」イベントを発行する必要がありますか?

4

2 に答える 2

7

コレクションから削除された後、破棄されたオブジェクトで「sync」イベントがトリガーされます。これが、コレクションが「同期」イベントを発生させない理由です。ただし、コレクションは「破棄」イベントを中継します。

于 2013-02-18T20:12:59.433 に答える
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がヒットするかどうかを確認できますか?

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
    }
});
于 2013-02-18T18:30:01.203 に答える