我需要将其他参数传递给Ember-Model的belongsTo。我让它使用自己的属性类型。但我也需要有关系。这有可能吗?
UserType = {
serialize: function(objectId) {
return {
__type: 'Pointer',
className: '_User',
objectId: objectId
};
},
deserialize: function(object) {
return object.objectId;
}
};
App.Movie = Ember.Model.extend({
objectId: Ember.attr(),
createdAt: Ember.attr(),
updatedAt: Ember.attr(),
owner: Ember.attr(UserType),
// owner: Ember.belongsTo('App.User', {
// key: 'objectId'
// }),
});
App.User = Ember.Model.extend({
objectId: Ember.attr(),
username: Ember.attr(),
email: Ember.attr(),
createdAt: Ember.attr(),
updatedAt: Ember.attr(),
});
App.User.primaryKey = 'objectId';
这是电影的JSON:
{
"ratings": [
{
"objectId": "AQWYN32UUo",
"value": 4
}
],
"title": "Inception",
"watched": true,
"year": "2010",
"owner": {
"__type": "Pointer",
"className": "_User",
"objectId": "AQWYN32UUo"
},
"createdAt": "2013-11-28T15:38:40.730Z",
"updatedAt": "2013-11-28T15:55:37.114Z",
"objectId": "0x5tdCcWiy"
},
谢谢
答案 0 :(得分:1)
我看到你现在在说什么,你需要覆盖getBelongsTo和s
这是默认实现
Ember.Model.reopen({
getBelongsTo: function(key, type, meta) {
var idOrAttrs = get(this, '_data.' + key),
record;
if (Ember.isNone(idOrAttrs)) {
return null;
}
if (meta.options.embedded) {
var primaryKey = get(type, 'primaryKey');
record = type.create({ isLoaded: false });
record.load(idOrAttrs[primaryKey], idOrAttrs);
} else {
record = type.find(idOrAttrs);
}
return record;
}
});
serializeBelongsTo: function(key, meta) {
if (meta.options.embedded) {
var record = this.get(key);
return record ? record.toJSON() : null;
} else {
var primaryKey = get(meta.getType(), 'primaryKey');
return this.get(key + '.' + primaryKey);
}
}
您可以将其更改为此类
owner: Ember.belongsTo('App.User', {key: 'owner', serializer:UserType}),
Ember.Model.reopen({
getBelongsTo: function(key, type, meta) {
var idOrAttrs = get(this, '_data.' + key),
record;
if (Ember.isNone(idOrAttrs)) {
return null;
}
// THIS IS NEW
if (meta.options.serializer){
idOrAttrs = meta.options.serializer.deserialize(idOrAttrs);
}
if (meta.options.embedded) {
var primaryKey = get(type, 'primaryKey');
record = type.create({ isLoaded: false });
record.load(idOrAttrs[primaryKey], idOrAttrs);
} else {
record = type.find(idOrAttrs);
}
return record;
},
serializeBelongsTo: function(key, meta) {
if (meta.options.embedded) {
var record = this.get(key);
return record ? record.toJSON() : null;
} else {
// THIS IS NEW
if(meta.options.serializer){
return meta.options.serializer.serialize(record);
}
var primaryKey = get(meta.getType(), 'primaryKey');
return this.get(key + '.' + primaryKey);
}
}
});