我正在从Ember数据0.13迁移到1.0.0 beta.根据doc
https://github.com/emberjs/data/blob/master/TRANSITION.md,现在有每种类型的适配器和每种类型的序列化器.
这意味着我无法再使用主键和身份验证的某些特定覆盖来定义“myRestAdapter”.我现在需要为每个模型类型实现此代码,从而导致复制相同代码的xx倍.
Ember数据中的代码0.13:
App.AuthenticatedRestAdapter = DS.RESTAdapter.extend({ serializer: DS.RESTSerializer.extend({ primaryKey: function() { return '_id'; } }),ajax: function (url,type,hash) { hash = hash || {}; hash.headers = hash.headers || {}; hash.headers['Authorization'] = App.Store.authToken; return this._super(url,hash); } });
Ember数据1.0.0中的代码(仅用于将主键设置为_id而不是_id:
App.AuthorSerializer = DS.RESTSerializer.extend({ normalize: function (type,property,hash) { // property will be "post" for the post and "comments" for the // comments (the name in the payload) // normalize the `_id` var json = { id: hash._id }; delete hash._id; // normalize the underscored properties for (var prop in hash) { json[prop.camelize()] = hash[prop]; } // delegate to any type-specific normalizations return this._super(type,json); } });
我是否理解我需要为每个需要_id作为主键的模型复制同一个块?是否已经没有办法为整个应用程序指定一次?
解决方法
由于代码接缝是类型不可知的,为什么你不只是创建模型可以扩展的自定义序列化器,例如:
App.Serializer = DS.RESTSerializer.extend({ normalize: function (type,hash,property) { // property will be "post" for the post and "comments" for the // comments (the name in the payload) // normalize the `_id` var json = { id: hash._id }; delete hash._id; // normalize the underscored properties for (var prop in hash) { json[prop.camelize()] = hash[prop]; } // delegate to any type-specific normalizations return this._super(type,json,property); } });
然后对所有模型使用App.Serializer:
App.AuthorSerializer = App.Serializer.extend(); App.PostSerializer = App.Serializer.extend(); ...
希望能帮助到你.