对于ember-data 1.0.0-beta6
,我有这个序列化器:
SettingsApp.CompanySerializer = SettingsApp.MetaRESTSerializer.extend({
extractSingle: function(store, type, payload, id, requestType) {
var company = payload;
company.company.nodeType = payload.company.type;
company.company.invoiceLanguage = payload.company['invoice-language'];
company.company.companyLanguage = payload.company['company-language'];
company.company.paymentMethod = payload.company['payement-method'];
// TODO: delete original properties?
return this._super(store, type, company, id, requestType);
}
});
如何进行逆操作?也就是说,在将模型发布到服务器之前,如何将模型映射到json?
答案 0 :(得分:1)
您需要查看三个挂钩,代码可以位于此处https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/rest_serializer.js#L760
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = this._super(record, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param record
@param options
*/
serialize: function(record, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends camelized root keys.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(hash, type, record, options) {
var root = Ember.String.camelize(type.typeKey);
hash[root] = this.serialize(record, options);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "Type"] = Ember.String.camelize(belongsTo.constructor.typeKey);
}