从Ember中的控制器访问模型的正确方法是什么

时间:2017-01-23 10:00:05

标签: ember.js ember-model

我想知道从控制器访问模型的正确方法是什么?

我注意到在控制器的 init 中,模型仍为空

#controller.js

<input type="radio" id="male" name="gender" value="male"> Male
<input type="radio" id="female" name="gender" value="female"> Female

但是 setupController 方法具有填充的模型。因此,目前我从 setupController 调用控制器的方法,并在那里传递模型。这样好吗?

我在想控制器中会有一个回调方法,在设置控制器时会自动调用。

2 个答案:

答案 0 :(得分:2)

route.js

  model() {
    return this.store.findAll("post");
  },  
  setupController(controller, model){
    controller.set('model', model);
  }

这将给出控制台日志模型,它是post对象的集合。

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);
      }

并且您不必在控制器上进行任何设置,这也可以在控制器上为您提供模型。

答案 1 :(得分:1)

setupController hook方法将model设置为控制器的属性。

setupController(controller,model){
 this._super(...arguments);
}

您可以像控制器中的普通其他属性一样获取模型。 this.get('model')

相关问题