我正在将余烬应用程序从ember-data v0.13 迁移到 v1.0.0 。
在版本v0.13中,RESTSerializer
曾经有一个实现回调,允许我将rails STI模型映射到ember模型。
因此,当我得到不同类型的事件列表时,我会将每个事件转换为适当的余烬模型
"events": [
{
"id": 1,
"type": "cash_inflow_event",
"time": "2012-05-31T00:00:00-03:00",
"value": 30000
},
{
"id": 2,
"type": "asset_bought_event",
"asset_id": 119,
"time": "2012-08-16T00:00:00-03:00",
"quantity": 100
}
]
Ember模特
App.Event = DS.Model.extend({...})
App.AssetBoughtEventMixin = Em.Mixin.create({...})
App.AssetBoughtEvent = App.Event.extend(App.AssetBoughtEventMixin)
App.CashInflowEventMixin = Em.Mixin.create({...})
App.CashInflowEvent = App.Event.extend(App.CashInflowEventMixin)
Ember-data code v0.13创建了类似STI的余烬模型
App.RESTSerializer = DS.RESTSerializer.extend({
materialize:function (record, serialized, prematerialized) {
var type = serialized.type;
if (type) {
var mixin = App.get(type.classify() + 'Mixin');
var klass = App.get(type.classify());
record.constructor = klass;
record.reopen(mixin);
}
this._super(record, serialized, prematerialized);
},
rootForType:function (type) {
if (type.__super__.constructor == DS.Model) {
return this._super(type);
}
else {
return this._super(type.__super__.constructor);
}
}
});
如何在ember-data v1.0.0 中做同样的事情?
答案 0 :(得分:2)
我想我有一个解决方案......
模型上有一个setupData回调。 我做了以下
App.Event = DS.Model.extend({
...
setupData:function (data, partial) {
var type = data.type;
if (type) {
var mixin = App.get(type.classify() + 'Mixin');
this.reopen(mixin);
}
delete data.type;
this._super(data, partial);
},
eachAttribute: function() {
if(this.get('type')){
var constructor = App.get(this.get('type').classify());
constructor.eachAttribute.apply(constructor, arguments);
}
this._super.apply(this, arguments);
}
});
Ember专家,这是一个好主意吗?
答案 1 :(得分:1)
首先,由于您使用的是Rails,因此您可能需要使用ActiveModelAdapter&从序列化程序扩展自定义序列化程序:
App.ApplicationAdapter = DS.ActiveModelAdapter;
App.ApplicationSerializer = DS.ActiveModelSerializer.extend({...});
您的自定义序列化程序应该覆盖typeForRoot
&可能是normalize
。以下是这些方法现在的样子:
DS.ActiveModelSerializer#typeForRoot
:
typeForRoot: function(root) {
var camelized = Ember.String.camelize(root);
return Ember.String.singularize(camelized);
}
DS.JSONSerializer#normalize
:
normalize: function(type, hash) {
if (!hash) { return hash; }
this.applyTransforms(type, hash);
return hash;
}