我想知道从控制器访问模型的正确方法是什么?
我注意到在控制器的初始化中,模型仍然为空
#controller.js
init(){
console.log(this.model); // IS NULL
}
但是setupController方法具有填充的模型。因此,当前我正在从setupController调用控制器的方法,并在那儿传递模型。这样好吗
我以为控制器中将有一个回调方法,该方法将在设置控制器时自动调用。
route.js
model() {
return this.store.findAll("post");
},
setupController(controller, model){
controller.set('model', model);
}
这将提供控制台日志模型,该模型是发布对象的集合。
controller.js
init(){
console.log(this.model);
}
我们大多数时候都会这样做,特别是如果您使用RSVP保证您选择了控制器上的模型。
例子
model(params) {
return Ember.RSVP.hash({
lecture: this.store.findRecord('section', params.section_id).then((section)=>{
return this.store.createRecord('lecture',{
section: section
});
}),
section:this.store.findRecord('section', params.section_id),
course: this.store.query('course',{filter:{section_id:params.section_id}})
});
},
setupController(controller,model){
controller.set('model', model.lecture);
controller.set('section', model.section);
controller.set('course', model.course);
}
请注意,如果您仅在路线上拥有简单模型
model(params) {
return this.store.findRecord('course', params.course_id);
}
而且您不必在控制器上进行任何设置,这也可能使您在控制器上进行建模。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句