Skip to content

Commit

Permalink
Use built-in Backbone.Collection.prototype.set
Browse files Browse the repository at this point in the history
... which already performs intelligent adds/updates/removes.
  • Loading branch information
colllin committed Jul 1, 2015
1 parent 68ca75b commit f7b47b8
Showing 1 changed file with 1 addition and 31 deletions.
32 changes: 1 addition & 31 deletions backbone-nested-models.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,38 +43,8 @@
// within the collection.
if(val instanceof Collection || val instanceof Array){
val = val.models || val;
modelsToAdd = _.clone(val);

relation.each(function(model, i) {

// If the model does not have an "id" skip logic to detect if it already
// exists and simply add it to the collection
if(typeof model[id] == 'undefined') return;

// If the incoming model also exists within the existing collection,
// call set on that model. If it doesn't exist in the incoming array,
// then add it to a list that will be removed.
var rModel = _.find(val, function(_model) {
return _model[id] === model[id];
});

if(rModel) {
model.set(rModel.toJSON ? rModel.toJSON() : rModel);

// Remove the model from the incoming list because all remaining models
// will be added to the relation
modelsToAdd.splice(i,1);
} else {
modelsToRemove.push(model);
}

});

_.each(modelsToRemove, function(model) {
relation.remove(model);
});

relation.add(modelsToAdd);
relation.set(val);

} else {

Expand Down

0 comments on commit f7b47b8

Please sign in to comment.