4

我正在将 ember 应用程序从 ember-data v0.13 迁移v1.0.0

在 v0.13 版本中,RESTSerializer曾经有一个物化回调,允许我将 rails STI 模型映射到 ember 模型。

因此,当我获得不同类型的事件列表时,我会将它们中的每一个转换为适当的 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
    }
]

余烬模型

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)

创建类似 STI 的 ember 模型的 Ember 数据代码 v0.13

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中做同样的事情?

4

2 回答 2

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 专家,这是个好主意吗?

于 2013-10-26T00:08:59.380 回答
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;
}
于 2013-10-25T06:51:32.330 回答