Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the backbone localstorage

The javascript one seems pretty simple, just localStorage.clear().

Is there anything similar to that for the backbone localstorage, and if not, can someone point me in the right direction on how to do it.

I was thinking about doing something like this:

localStorage.each(localStorage.delete(this))

except this wouldn't point to that element would it?

like image 414
prashn64 Avatar asked Mar 28 '12 16:03

prashn64


People also ask

How do I clear my localStorage?

Use the clear() method to delete all items in localStorage .

What does clear local storage mean?

Definition and Usage The clear() method removes all the Storage Object item for this domain. The clear() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.

How do I empty Sessionstorage?

We can get specified session storage using the getItem() method. We can clear the session storage by using the clear() method.


2 Answers

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();
}
like image 115
dc- Avatar answered Sep 18 '22 10:09

dc-


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..

like image 23
Sören Kampschroer Avatar answered Sep 18 '22 10:09

Sören Kampschroer