In ember data, calling destroyRecord in a forEach loop is corrupting the loop?

邮差的信 提交于 2019-12-23 15:17:31

问题


I'm working on a simple Tag model for one of my projects. I've implemented something similar in Angular, but I wanted to give it a try in Ember. The model code is below

Tag = DS.Model.extend {
  name:DS.attr('string')
  user:DS.belongsTo('user')
  appliedTags:DS.hasMany('AppliedTag')

  obliterate:()->
    #destory the associated applied tags
    this.get('appliedTags').forEach( (appliedTag)->
      console.log(Ember.inspect(appliedTag))
      appliedTag.destoryRecord()
    )
    #destory the record
    this.destroyRecord()
}

fixtures = [
    id:1
    name:'Category 1'
    user:1
    appliedTags:[1,5]
]

Tag.reopenClass
  FIXTURES: fixtures

Everything is fine if I comment out appliedTag.destoryRecord(). However with it in, on the second time through the forEach loop, appliedTag is undefined.


回答1:


Modifying the contents of a collection while iterating will cause major issues. That's the issue that you're seeing here, you're destroying records, which modifies the collection that's being iterated. Ember's hasMany collection will remove records when they are removed from the store/destroyed. The easiest solution is to copy the contents to a different array that won't get modified when you perform those kinds of operations.

this.get('appliedTags').toArray().forEach( (appliedTag)->
  console.log(Ember.inspect(appliedTag))
  appliedTag.destoryRecord()
)


来源:https://stackoverflow.com/questions/25715738/in-ember-data-calling-destroyrecord-in-a-foreach-loop-is-corrupting-the-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!