“How” to save an entire collection in Backbone.js - Backbone.sync or jQuery.ajax?

前端 未结 11 1278
醉梦人生
醉梦人生 2020-11-28 19:45

I am well aware it can be done and I\'ve looked at quite a few places (including: Best practice for saving an entire collection?). But I\'m still not clear \"exactly how\"

11条回答
  •  -上瘾入骨i
    2020-11-28 20:21

    Old thread i know, what i ended up doing is the following:

    Backbone.Collection.prototype.save = function (options) {
                // create a tmp collection, with the changed models, and the url
                var tmpCollection = new Backbone.Collection( this.changed() );
                tmpCollection.url = this.url;
                // sync
                Backbone.sync("create", tmpCollection, options);
            };
            Backbone.Collection.prototype.changed = function (options) {
                // return only the changed models.
                return this.models.filter( function(m){
                    return m.hasChanged()
                });
            };
    // and sync the diffs.
    self.userCollection.save();
    

    Pretty straint foreward :)

提交回复
热议问题