背景
最近, Tom Dale 宣布“嵌入式加载现已回归!”。然而,它似乎只完全支持加载场景。目前尚不清楚序列化嵌入式关联是否仍在开发中,或者是否希望用户通过构建自定义序列化程序自己实现它。
要求
我的嵌入式关联的 JSON 如下所示:
{
inputs: [
{
id: 1,
name: "Favorite Color",
type: "SelectInput",
options: {
choices: [ 'red', 'green', 'yellow' ]
}
},
{
id: 2,
name: "email",
type: "TextInput",
options: {}
}
]
}
我相信表示这一点的“余烬方式”是构建一个自定义序列化程序,它将我的 JSON 转换为如下模型:
App.Choice = DS.Model.extend({
name: DS.attr( 'string' ),
input: DS.belongsTo( 'App.Input' )
});
App.Input = DS.Model.extend({
name: DS.attr( 'string' ),
type: DS.attr( 'string' ),
choices: DS.hasMany( 'App.Choice' )
});
尝试的解决方案
以下解决方案大多有效,但感觉我一定是“做错了”,因为我不得不对这么多代码进行逆向工程和子类化。
Customizer.MyRESTAdapter = DS.RESTAdapter.extend({
dirtyRecordsForAttributeChange: function(dirtySet, record, attributeName, newValue, oldValue) {
if(record.constructor === Customizer.Choice) {
if(newValue === oldValue) { return; }
var input = null;
if (attributeName == 'name') {
input = record.get('input');
}
else if(attributeName == 'input') {
input = newValue;
}
if( input ) {
dirtySet.add( input );
}
}
else {
this._super(dirtySet, record, attributeName, newValue, oldValue);
}
},
dirtyRecordsForBelongsToChange: function(dirtySet, child, relationship) {
if(child.constructor === Customizer.Choice) {
var input = child.get( 'input' );
if( input ) {
dirtySet.add( input );
}
}
else {
this._super(dirtySet, child, relationship);
}
},
dirtyRecordsForHasManyChange: function(dirtySet, parent, relationship) {
this._super(dirtySet, parent, relationship);
}
});
Customizer.MyRESTSerializer = DS.RESTSerializer.extend({
init: function() {
this._super();
this.mappings.set( 'Customizer.Input', { choices: { embedded: 'load' } } );
},
extractEmbeddedHasMany: function(type, hash, key) {
if(type == Customizer.Input) {
if(!(hash['options'] && hash['options']['choices'])) { return null; }
var choices = [];
hash['options']['choices'].forEach(function(choice, i){
var choiceId = hash['id'] + '_' + i;
var inputId = hash['id'];
choices[i] = { id: choiceId, input_id: inputId, name: choice };
});
return choices;
}
return this._super(type, hash, key);
},
addHasMany: function(data, record, key, relationship) {
this._super(data, record, key, relationship);
if( key === 'choices' ) {
var choices = record.get('choices').map(function( choice ){
return choice.get( 'name' );
});
data['options'] = data['options'] || {};
data['options']['choices'] = choices;
}
}
});
Customizer.store = DS.Store.create({
revision: 10,
adapter: Customizer.MyRESTAdapter.create({
namespace: 'api/v1',
bulkCommit: false,
serializer: Customizer.MyRESTSerializer
})
})
请求反馈
- 这是正确的道路吗?
- ember 团队是否正在积极寻找更好的方法来做到这一点?