所以我有东西。它还没有完成,也没有完全干净,但它可以工作。基本上,我使用 mixin 来完全绕过 Ember 关联。我确信这可以滚动到适配器或商店中,但现在这可行。
多态模型通过带有 itemId 和 itemType 的 JSON:
App.Follow = DS.Model.extend
user: DS.belongsTo('App.User')
itemId: DS.attr("number")
itemType: DS.attr("string")
我在与之关联的模型中添加了一个 mixin:
App.Hashtag = DS.Model.extend App.Polymorphicable,
follows:(->
name: DS.attr("string")
@polymorphicFilter(App.Follow, "Hashtag")
).property('changeCount') #changeCount gives us something to bind to
followers: (->
@get('follows').map((item)->item.get('user'))
).property('follows')
mixin 实现了三种方法,一种更新changeCount,一种返回模型的类型,以及通过itemType 和id 过滤模型的polymorphicFilter 方法:
App.Polymorphicable = Ember.Mixin.create
changeCount: 1
polymorphicFilter: (model, itemType)->
App.store.filter model,
(data) =>
if data.get('itemId')
@get('id') is data.get('itemId').toString() and data.get('itemType') is itemType
itemType:()->
@constructor.toString().split('.')[1]
updatePolymorphicRelationships:()->
@incrementProperty('changeCount')
除了必须调用 updatePolymorphicRelationship 以确保绑定触发之外,控制器层受到保护,不会出现所有这些问题:
App.HashtagController = Ember.ObjectController.extend
follow:()->
App.Follow.createRecord({
user: @get('currentUserController.content')
itemId: @get('id')
itemType: @get('content').itemType()
})
#this provides a way to bind and update. Could be refactored into a didSave()
#callback on the polymorphic model.
@get('content').updatePolymorphicRelationships()
App.store.commit()
这就是我目前所拥有的。我试图将东西保留在模型层中,因为它只是从适配器层移除了一步。如果看起来 Ember Data 将来根本不会考虑多态,那么将这一切提升到更高的水平是有意义的,但就目前而言,这可行并且让我的控制器(相对)干净。