Created
December 22, 2011 19:34
-
-
Save kingbuzzman/1511546 to your computer and use it in GitHub Desktop.
update for Backbone.Collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| update: function(options){ | |
| options = options || {}; | |
| var collection = this, success = options.success; | |
| options.success = function(resp, status, xhr){ | |
| var changed = false; | |
| var collectionIds = []; // store the ids as we add them | |
| var toDelete = []; // store all the models to remove | |
| var onChange = function() { | |
| this.unbind("change", onChange); | |
| changed = true; | |
| }; | |
| // add/ update | |
| _(collection.parse(resp, xhr)).each(function(item){ | |
| var model = collection.get(item.id); | |
| var triggerChange = {}; | |
| var key, update = {}; | |
| if (!model){ | |
| collection.add(item, options); | |
| changed = true; | |
| collectionIds.push(item.id); // update ids | |
| } else { | |
| model.bind("change", onChange); | |
| model.set(item); | |
| model.unbind("change", onChange); // remove binding that may have not been triggered | |
| collectionIds.push(model.id); // update ids | |
| } | |
| }); | |
| // generate a list of models to remove from the collection | |
| if (collection.length !== collectionIds.length) { | |
| toDelete = collection.filter(function(model){ | |
| return collectionIds.indexOf(model.id) === -1; | |
| }); | |
| } | |
| // remove all the models that were not sent back | |
| if (toDelete.length) { | |
| changed = true; | |
| collection.remove(toDelete, options); | |
| } | |
| // trigger collection events | |
| if (!options.silent && changed) { | |
| collection.trigger('changed', collection, options); | |
| } | |
| if (success) { | |
| success(collection, resp); | |
| } | |
| }; | |
| return (this.sync || Backbone.sync).call(this, 'read', this, options); | |
| }, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment