Skip to content

Commit

Permalink
added an option for the method cleanup and destroy refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
int committed Mar 3, 2014
1 parent 3dd14f4 commit e35563e
Showing 1 changed file with 7 additions and 15 deletions.
22 changes: 7 additions & 15 deletions backbone-associations.js
Original file line number Diff line number Diff line change
Expand Up @@ -615,15 +615,18 @@
// Call this if you want to set an `AssociatedModel` to a falsy value like undefined/null directly.
// Not calling this will leak memory and have wrong parents.
// See test case "parent relations"
cleanup:function () {
cleanup:function (options) {
options = options || {};

_.each(this.relations, function (relation) {
var val = this.attributes[relation.key];
if(val) {
val._proxyCallback && val.off("all", val._proxyCallback, this);
val.parents = _.difference(val.parents, [this]);
}
}, this);
this.off();

(!options.listen) && this.off();
},

// Override destroy to perform house-keeping on `parents` collection
Expand All @@ -632,32 +635,21 @@
options = _.defaults(options, {remove_references: true});
var model = this;

// Remove references to `model` in objects which have `model` as their parent
var removeReferences = function() {
_.each(model.relations, function (relation) {
var val = model.attributes[relation.key];
if(val) {
val._proxyCallback && val.off("all", val._proxyCallback, model);
val.parents = _.difference(val.parents, [model])
}
});
};

if(options.remove_references && options.wait) {
// Proxy success implementation
var success = options.success;

// Substitute with an implementation which will remove references to `model`
options.success = function (resp) {
if (success) success(model, resp, options);
removeReferences();
model.cleanup({listen: true});
}
}
// Call the base implementation
var xhr = ModelProto.destroy.apply(this, [options]);

if(options.remove_references && !options.wait) {
removeReferences();
model.cleanup({listen: true});
}

return xhr;
Expand Down

0 comments on commit e35563e

Please sign in to comment.