1

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!

nodesto
  • 505
  • 2
  • 8
  • 24
  • if it a complete code problem is in async type of fetch. to iterate over collection you have to wait until fetch is done. – Evgeniy Oct 06 '14 at 07:01
  • The iteration is initiated when clicking a button - this is done when the data has been fetched, so I don't think this is the issue – nodesto Oct 06 '14 at 15:38
  • could u please attach `console.log(model)` output inside a loop ? – Evgeniy Oct 07 '14 at 05:14
  • The console.log outputs the models without any problem - please see the solution below – nodesto Oct 07 '14 at 16:53

1 Answers1

1

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.

nodesto
  • 505
  • 2
  • 8
  • 24
  • can you elaborate by how the internal iterations gets mess up by the deletion of models? – akantoword Jun 03 '16 at 23:07
  • The iteration does not take account for the element that is suddenly missing. Therefore the method above works, or using a for-loop that runs in reverse – nodesto Jun 04 '16 at 10:07