在垃圾数据中,在forEach循环中调用destroyRecord会破坏循环? [英] In ember data, calling destroyRecord in a forEach loop is corrupting the loop?
问题描述
Tag = DS.Model.extend {
name:DS.attr('string' )
用户:DS.belongsTo('user')
appliedTags:DS.hasMany('AppliedTag')
obliterate:() - >
#destory相关应用的标签
this.get('appliedTags')。forEach((appliedTag))>
console.log(Ember.inspect(appliedTag))
appliedTag.destoryRecord()
)
#destory记录
this.destroyRecord()
}
fixtures = [
id:1
名称:'类别1'
用户:1
appliedTags:[1,5]
]
Tag.reopenClass
FIXTURES:灯具
如果我注释掉 appliedTag.destoryRecord()
。但是,在第二次通过 forEach
循环时, appliedTag
是未定义 。
在迭代时修改集合的内容将导致重大问题。这是你在这里看到的问题,你正在破坏记录,修改正在迭代的集合。 Ember's hasMany collection将会从存储中删除记录/销毁记录。最简单的解决方法是将内容复制到不同的数组,执行这些操作时不会被修改。
this.get('appliedTags')。toArray()。forEach((appliedTag) - >
console.log(Ember.inspect(appliedTag))
appliedTag.destoryRecord()
)
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.
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()
)
这篇关于在垃圾数据中,在forEach循环中调用destroyRecord会破坏循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!