【发布时间】:2016-10-05 02:23:32
【问题描述】:
在我的 EmberJS 应用程序中,我正在显示约会列表。在 AppointmentController 中的一个操作中,我需要获取约会所有者,但所有者总是返回“未定义”。
我的文件:
models/appointment.js
import DS from 'ember-data';
export default DS.Model.extend({
appointmentStatus: DS.attr('number'),
owner: DS.hasMany('person'),
date: DS.attr('Date')
});
models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string')
});
templates/appointmentlist.js
{{#each appointment in controller}}
<div>
{{appointment.date}} <button type="button" {{action 'doIt'}}>Do something!</button>
</div>
{{/each }}
controllers/appointmentlist.js
export default Ember.ArrayController.extend({
itemController: 'appointment'
});
controllers/appointment.js
export default Ember.ObjectController.extend({
actions:{
doIt: function(){
var appointment = this.get('model');
var owner = appointment.get('owner'); //returns undefined
//Do something with owner
}
}
});
现在,我知道我可以将 owner-property 更改为 owner: DS.hasMany('person', {async: true}),然后处理从 appointment.get('owner'); 返回的承诺,但这不是我想要的。
我发现如果我在约会列表模板中执行此{{appointment.owner}} 或此{{appointment.owner.name}},则会从服务器获取所有者记录。所以我猜 Ember 不会加载关系,除非它们在模板中使用。
我认为我的问题的解决方案是使用约会列表路由来获取belongsTo关系中的记录。但我不知道怎么做。
也许是这样的?
routes/appointmentlist.js
export default Ember.Route.extend({
model: function() {
return this.store.find('appointment');
},
afterModel: function(appointments){
//what to do
}
});
编辑
我这样做了:
routes/appointmentlist.js
export default Ember.Route.extend({
model: function() {
return this.store.find('appointment');
},
afterModel: function(appointments){
$.each(appointments.content, function(i, appointment){
var owner= appointment.get('owner')
});
}
});
它有效,但我不喜欢这个解决方案......
【问题讨论】:
标签: ember.js ember-data