Backbone Model.destroy() Limited
Solution 1:
Is this an intentional limitation within Backbone to keep you from deleting 1000 records in one shot or a browser limitation on the number of relatively simultaneous DELETE methods?
No.
The problem is you are munging the collection on each iteration. Consider the following.
Say you start off with a collection of 10 models:
// pretend this collection has 10 models [m0,m1,m2,m3,m4,m5,m6,m7,m8,m9]
collection.each(function(model,i) {
model.destroy();
});
On your first iteration, your collection.length === 10
and the arguments to collection.each
will be m0
and 0
. So you call, m0.destroy()
which lives at index 0.
At the end of the first iteration your collection
contains the following models
[m1,m2,m3,m4,m5,m6,m7,m8,m9]
The following is where the problem starts:
Now for your second iteration your collection.length === 9
. The each
function is now on its second iteration and grabbing the model at index of 1, and that's where model 2 lives. So the arguments into each
are m2,1
. You then call m2.destroy()
and remove that from the collection.
At the end of the second iteration your collection contains the following:
[m1,m3,m4,m5,m6,m7,m8,m9]
The third iteration, your index will be 2 and m4.destroy()
will be called. leaving you with:
[m1,m3,m5,m6,m7,m8,m9].
This happens until the index is greater than collection.length
and then stops. Leaving you with unwanted models in your collection.
The following should work for you:
while ( (model=collection.shift()) ) {
model.destroy()
}
Solution 2:
Agree to previous answers, you are not allow to do that.
Very quickly, what I would do in that case:
collection.map(function (model) {
return model.id;
}).each(function (id) {
collection.get(id).destroy();
});
Solution 3:
Have you tried removing the model first from the collection using Backbone.Collection.remove
? I think by calling model.destroy()
you are breaking the internal array of models handled by the collection.
Try it like this:
collection.each(function(model, i) {
collection.remove(model);
model.destroy();
});
Post a Comment for "Backbone Model.destroy() Limited"