Deewendra Shrestha
Deewendra Shrestha

Reputation: 2465

deleting multiple records from hasMany relation causes js error

I have simple models defined as :

        App.Answer = DS.Model.extend({
            name: DS.attr('string')
        });

        App.Question = DS.Model.extend({
            questionName: DS.attr('string'),
            answers: DS.hasMany('answer')
        });

I wanted the capability to add answers to question model and also be able to delete all the hasMany association with a click of a button. But when I call deleteRecord in a loop, it throws js error.The alternative approach was to introduce some delay after deleting each record which I don't think is the right way to do things.

Here is jsbin link to demonstrate the issue : http://jsbin.com/UleKodiC/2/ Click "add" button couple of times and then click "Delete all", it should give you js error that the model is undefined. But if you click of "Delete slow"(which does delayed delete), it deletes the records without error.

Thanks, Dee

Upvotes: 2

Views: 1720

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

You're modifying the collection you're iterating, that's generally bad mojo, the easy fix is to create a different list and iterate over it, while modifying the list you wanted to change.

var answers = this.get('model.answers'),
    list = answers.toArray();

list.forEach(function(answer) {  
  answer.deleteRecord();
  answers.removeObject(answer);
});

http://jsbin.com/uJopIcE/1/edit

Upvotes: 13

Related Questions