我有一条路线,有两个与之关联的模型,如下所示:
App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
sites: this.store.find('site'),
songs: this.store.find('song')
})
},
稍后,我需要能够检索 sites
模型中的第一个对象,以便进行如下所示的转换。我想我可以使用 setupController 设置模型,但是当处理上面描述的多个模型时,我不确定如何填写这部分:
setupController: function(controller, ???) {
controller.set('model1', ???);
controller.set('model2', ???);
}
最后,我希望能够检索 model1 中的第一个对象(如上所述,它是 site
的多个实例)
afterModel: function() {
firstRecord = this.('sites').objectAt(0);
this.transitionTo('site', firstRecord.id);
}
也有可能是我没有正确设计我的应用程序。在本例中,sites 是我构建的一个组件,它在几个不同的 Controller 中显示不同的站点。 Controller 依赖于该组件,因为它们需要知道选择了哪个站点才能执行自己的操作。因此,在需要访问组件的 Controller 中,我会执行以下操作:
{{site-nav sites=sites}}
其中 site-nav
是我的组件。它需要自己的模型,就像 Controller 本身一样。
最佳答案
首先,您需要稍微修改模型 Hook ,以确保保持在正确的范围内:
model:function(){
var self = this;
return Ember.RSVP.hash({
sites: self.store.find('site'),
songs: self.store.find('song')
})
}
要在setupController
中获取不同的模型,您只需从第二个参数访问它,如下所示:
setupController:function(controller,models) {
controller.set('sites',models.sites);
controller.set('songs',models.songs);
}
afterModel
提供两个参数,第一个参数是路线的已解析模型,因此您可以这样做:
afterModel:function(models){
var site = models.sites.get('firstObject');
this.transitionTo('site',site);
}
关于javascript - Ember JS : retrieving model from route when multiple models are retrieved,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23331554/