Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 835
Deewendra Shrestha Avatar asked Jan 21 '26 09:01

Deewendra Shrestha


1 Answers

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

like image 89
Kingpin2k Avatar answered Jan 25 '26 18:01

Kingpin2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!