ember / ember-data belongsTo和hasMany没有按预期更新

时间:2014-06-24 16:13:09

标签: ember.js ember-data

我有两种模式:

App.Focusarea = DS.Model.extend
    definition: DS.attr('string')
    theme: DS.belongsTo('theme',
        async: true
    )

App.Theme = DS.Model.extend
    definition: DS.attr('string')
    focusareas: DS.hasMany('focusarea',
        async: true
    )

创建其中一个时,我想将焦点区域与该主题相关联

theme = store.createRecord("theme",
    id: 3
    definition: 'theme definition'
)

focusarea = store.createRecord("focusarea",
    id: 4
    definition: 'focusarea definition'
)

theme.get("focusareas").then (focusareas) ->
    focusareas.pushObject focusarea
    theme.save()

但是当我运行我的测试时

    theme.get('focusareas').then (focusareas)->
        expect(focusareas.toArray.length).to.equal(1)

失败 - focusareas.toArray.length等于0,换句话说,关联失败。 我做错了什么或我错过了什么?任何帮助将不胜感激。

更新

想出来,theme.get(' focusareas')返回一个未解决的承诺,即0,当解决时将返回1,例如:

focusareas = theme.get('focusareas')
focusareas.then ->
    console.log focusareas.get('length') #=1

store.find('theme', 4).then (theme)->
    theme.get('focusareas').then ->
        expect(theme.get('focusareas').get('length')).to.equal(1)

换句话说

store.find('theme', 4).then (theme)->
    theme.get('focusareas').then ->
        theme.get('focusareas').forEach (item) ->
            console.log(item.get('definition')) #'focusarea definition'
            item.get('theme').then ->
                console.log(item.get('theme').get('definition')) #'theme definition'

我想我应该只是RTFM!

1 个答案:

答案 0 :(得分:0)

在对象初始化期间,您需要将focusareas分配给getter和setter可以使用的某种集合。在这种情况下,ArrayProxy可以很好地工作。甚至你可以用?

自动对物品进行排序
theme = store.createRecord("theme",
    id: 3
    definition: 'theme definition',
    focusareas: Ember.ArrayProxy.createWithMixins Ember.SortableMixin,
      content: [],
      sortProperties: ['id'], // Set this to any object property
      sortAscending: true
)

希望有所帮助!