在Ember中,pushObject调用假定的回调,但removeObject不调用

时间:2014-12-06 02:45:55

标签: arrays ember.js observers

我有以下WorkSpec项目控制器,它控制复选框状态:

ContractorApp.WorkSpecController = Em.ObjectController.extend
  needs: ['account']
  selected: (->
    work_spec = @get 'content'
    work_specializations = @get 'controllers.account.work_specializations'
    work_specializations.contains work_spec
    ).property()

  selection_changed: (->
    work_spec = @get 'content'
    work_specializations = @get 'controllers.account.work_specializations'

    limit = @get 'controllers.account.specialization_limit'

    if @get( 'selected' ) && work_specializations.get('length') < limit
      work_specializations.pushObject work_spec
    else
      work_specializations.removeObject work_spec
    ).observes('selected')

如您所见,work_specializations是父工作专业化的集合: 我想控制(work_specializations.get('length')&lt; limit)向数组添加元素。

我在模型中获得观察者的问题包含work_specializations数组:

ContractorApp.ContractorProfile = DS.Model.extend
  work_specializations: DS.hasMany "work_specialization"
  on_spec_change: ( ->
    ws_ids = @get( 'work_specializations').map (ws)->
      ws.get 'id'
    @set( 'work_specialization_ids', ws_ids )
  ).observes 'work_specializations'

由于某种原因,调用'work_specializations.pushObject work_spec'调用模型的回调但其对应的removeObject不调用。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您正在观察集合本身,而不是正在添加或删除的项目。第一次改变可能是第一次引发观察。

on_spec_change: ( ->
  ws_ids = @get( 'work_specializations').map (ws)->
    ws.get 'id'
  @set( 'work_specialization_ids', ws_ids )
).observes 'work_specializations.[]'