Destroy all models in Backbone collection (persisted in local storage)

1.2k views Asked by At

How do I delete all models in my collection (persisted in local storage)?

The models are fetched from local storage - I want the models to be destroyed both at the client and also in local storage.

// Model + Collection
App.Models.Task = Backbone.Model.extend({
    defaults: {
        text: 'N/A'
    }
});

App.Collections.Tasks = Backbone.Collection.extend({
    model: App.Models.Task,
    localStorage: new Backbone.LocalStorage("task")
});


// Create collection and fetch tasks 
var tasks = new App.Collections.Tasks();
tasks.fetch(); // collection is now populated with 4 tasks


// Delete all models (both at client and local storage)
tasks.each(function(model) {
   model.destroy();
})

From running this, I destroy only some of the models - this error occurs and prevents the rest from being destroyed:

Uncaught TypeError: Cannot read property 'destroy' of undefined

Any help on this is greatly appreciated!

1

There are 1 answers

2
nodesto On BEST ANSWER

I found the solution:

_.invoke(tasks.toArray(), 'destroy');

Apparently, using the .each to destroy models is a bad practice, since the internal iteration gets messed up by the continual deletion of models.