How to clear the backbone localstorage
Few ways you can do this from the Collection, but whichever way you choose, you have to call destroy on each model, which will run sync and destroy it on both the client-side and server-side (which localStorage is acting as).
collection.each(function(model) {
model.destroy();
}
)
Update
Per comments, doesn't look like this works anymore. Since this is still marked as the answer, including answer that should work below, per skcin7
.
while ((model=collection.shift()))
{ model.destroy();
}
I know this kind of feels like grave digging, but i've been looking for a solution to this for a while now and none of the above snippets seemed to work for me. I always ended up having the size of the collection decreased by half, no matter how i tried it.
So after a decent amount of fiddling, i came up with this:
var length = collection.length;
for (var i = 0; i < length; i++) {
collection.at(0).destroy();
}
Backbone is removing items "on the fly", so if you have 40 items you won't be able to delete the 21. item because there are only 20 items left. Strangely enough this also seems to affect the collection.each() function which really seems like a bug to me..