我尝试像这样手动添加数据到模型
beforeModel: function() {
var scope =this;
Ember.$.getJSON('/restURL').then(function(response){
scope.store.pushPayload('consultation',response);
},
和数据成功加载,我可以在ember调试器中看到它,但我有一个问题-数据不呈现在视图上。
模板在application.hbs:
{{#each item in model}}
{{#link-to 'consultation' item}}{{item.remoteUser.name}}{{/link-to}}
{{/each}}
注意:当我使用this.store.find('consultation');
加载数据时,它的工作很好,但我有自定义URL,不能使用这种结构。
据我所知,您希望使用直接ajax调用加载磋商。您现在正在做的方式是,在beforeModel
中检索磋商,然后,由于您没有返回承诺,Ember立即在 ajax调用完成之前执行model
钩子。模型钩子中的this.store.find
可能会向服务器发出另一个可能无效的请求。最简单的方法就是
model: function() {
var store = this.store;
return Ember.$.getJSON('/restURL')
.then(function(response) {
store.pushPayload('consultation', response);
return store.all('consultation');
});
}
注意store.all
的使用,它是存储区中所有该类型对象的动态集合。
您还可以考虑将逻辑分解为beforeModel
和model
,如:
beforeModel: function() {
return Ember.$.getJSON('/restURL')
// this binding style is a matter of personal preference :-)
.then(this.store.pushPayload.bind(this.store, 'consultation'))
},
model: function() {
return this.store.all('consultation');
}
您应该使用afterModel
钩子而不是beforeModel
,因为beforeModel
不用于数据聚合。beforeModel
发生在模型试图得到解析之前,它不能访问解析后的模型,所以你不能依靠它向模型添加额外的数据。
另一方面,afterModel
钩子将解析的模型作为第一个参数传入,所以你可以根据需要进一步修饰模型,你可以像model
钩子一样返回一个承诺。
看这个简单的例子:http://emberjs.jsbin.com/nukebe/1