If you use a Backbone.js Collection with an integrated LocalStorage to save your models, you might need to empty this collection and the LocalStorage, too.

Invoking reset() on the collection does not have the required effect because it does not clean the LocalStorage.

An approach often documented in the web is to simply iterate over the collection and calling distroy() on each model object:

collection.each(function(model) { model.destroy(); } )

This is not a fully reliable approach because manipulating a collection while you are iterating over it at the same time can have un-intended effects. Not all model objects might be destroyed at the end.

A better way to do this is to use underscore.js clone facilitites to first get a clone of the list. Iterating over this clone and destroying each model element will result in a savely cleaned up collection including its local storage.

_.chain(Todos.models).clone().each(function(model){
console.log('deleting model ' + model.id);
model.destroy();
});

Backbone.js empty Collection and LocalStorage

Post navigation


Leave a Reply