Save Backbone.js Model and update entire Collection

I would like to be able to call save() on a backbone model and have the backend return the entire collection of this model instead of only the changed attributes of the model. I would then like backbone to update the entire returned collection. The use case for this is the following:

A user has multiple addresses and can choose a shipping address from this collection. If she chooses a different shipping address from the collection the previous shipping address should be updated to the state of 'just another plain address'. For this the entire collection has to be updated instead of only the changed model.

Is this somehow possible in backbone.js?

Thanks a lot in advance!


models that are bound to collections, contain their collection parent as a property. Also, since your returning a list of models, we can assume that it is always in a list.

mymodel = Backbone.Model.extend({
   parse: function (data) {
     if(this.collection && typeof(data) === 'array') {
        this.collection.reset(data);
     }
     return data;
   }
});

I do not think that overriding sync or breaking the expectations of what save returns is necessary here.

It would be simpler I guess to override save on the model, something on the lines of:

save: function (key, value, options) {
    var p = Model.prototype.save.call(this, key, value, options),
        self=this;
    if (this.collection) {
        p.done(function () { self.collection.fetch(); });
    }
    return p;
}

which will save using the normal save obtaining its promise, and then if saving was successful and the model is part of a collection, it will fetch the collection from the server.

Another way would be to bind to the model's change event, check if it belongs to a collection and fetch, but that would also happen on set .


Yep, it's possible. You'll need to override the sync function on the model

MyModel = Backbone.Model.extend({
  sync: function(method, model) {
    if (method === 'create') {
      //perform save logic and update the model's collection
    } else if (method === 'update') {
      //perform save logic and update the model's collection
    } else if (method === 'read') {
      ...
    } else if (method === 'destroy') {
      ...
    }
  }
});

Take a look at the Backbone.sync function for more information.

链接地址: http://www.djcxy.com/p/67136.html

上一篇: 将jQuery UI Sortable的顺序保存到Backbone.js集合中

下一篇: 保存Backbone.js模型并更新整个集合