【问题标题】:Deleting all objects in an association删除关联中的所有对象
【发布时间】:2012-11-04 09:47:16
【问题描述】:

给定一个看起来像这样的模型:

App.Parent = Ember.Model.extend(
    children: DS.attr.hasMany('App.Child')
)

App.Child = Ember.Model.extend(
    parent: DS.attr.belongsTo('App.Parent')
)

parent = App.Parent.find(1)

# How do I remove parent and all of it's children?
# This doesn't work since I'm removing elements from an array while iterating it
parent.get('children').forEach( c -> c.deleteRecord() )
parent.deleteRecord()

# Only removing the parent like this won't work either, 
# Ember-data generates some strange PUT requests for every child
parent.deleteRecord()

# I guess I could do this, but it feels really awkward and 
# wrong to use the adapter directly.
# And it also side-steps transactions making bulk updates impossible
App.store.adapter.deleteRecords(App.store, App.Child, parent.get('children'))
parent.deleteRecord()
App.store.commit()

有没有更直接的方法,只删除父级时会产生什么奇怪的 PUT 请求?

【问题讨论】:

    标签: javascript coffeescript ember.js ember-data


    【解决方案1】:

    也许使用 toArray() 方法 http://emberjs.com/api/classes/Ember.ArrayProxy.html#method_toArray 应该可以工作,因为您不再直接修改 ManyArray

    parent.get('children').toArray().forEach( c -> c.deleteRecord() )
    

    对于子节点上奇怪的 PUT 请求,这是因为删除父节点时,ember-data 将子节点上的父属性“无效”。

    【讨论】:

      【解决方案2】:

      纯 JavaScript 而不是 CoffeeScript,但我认为你可以转换:

      var children = parent.get('children'),
          i = children.length;
      
      while (i--) {
          children[i].deleteRecord();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-13
        • 2020-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多