编辑:我想我找到了解决方案。正如我在问题中所说,变量profiles
是一个承诺,所以我尝试了以下方法,它有效:
...
setupController: function(controller, model) {
controller.set('model', model);
var profiles = App.Profile.findAllByMaster(model.get('id'));
profiles.then(function(data) {
controller.set('profiles', data);
});
}
...
结束编辑
当我试图从setupController
挂钩中的另一个模型获取数据时,我遇到了错误:Assertion failed: an Ember.CollectionView's content must implement Ember.Array. You passed [object Object]
。
路由是MastersMaster
,其关联模型是Master
,并且我尝试获得属于当前Master
的Profiles
模型。
我没有使用Ember数据或类似的东西。它只是带有$.ajax调用的纯jQuery。
这很难解释,所以这里是代码摘录:
App.MastersMasterRoute = Ember.Route.extend({
model: function(params) {
return App.Master.find(params.master_id);
},
setupController: function(controller, model) {
controller.set('model', model);
// if I comment these two lines it works but I don't get the profiles (obviously)
var profiles = App.Profile.findAllByMaster(model.get('id'));
controller.set('profiles', profiles);
}
});
App.Profile = Ember.Object.extend({
id: null,
name: '',
master_id: null
});
App.Profile.reopenClass({
findAllByMaster: function(master_id) {
var profiles = Ember.A();
return $.ajax({
url: 'ajax/get.profiles.php',
type: 'GET',
dataType: 'json',
data: { master_id: master_id }
}).then(function(response) {
$.each(response, function(i, item) {
profiles.pushObject(App.Profile.create(item));
});
return profiles;
});
}
});
如果我在执行controller.set
之前console.log
变量profiles
,我会看到它是一个promise,而不是预期的Profile
对象数组。我想我以前必须履行诺言,但我不知道。
附言:对不起,我的英语:(
正如我在编辑中所说,问题是findAllByMaster
方法返回了一个promise,因此必须在将其分配给控制器的属性之前解决它。
我想有一种更优雅或更有效的方法来解决它,所以欢迎其他解决方案。