2017-01-23 62 views
0

我想知道什麼正確的方式來訪問模型控制器什麼是從Ember的控制器訪問模型的正確方法

我注意到,在控制器的初始化模式仍然是空

#controller.js

init(){ 
    console.log(this.model); // IS NULL 
} 

setupController方法有填充模型。因此,目前我正在從setupController調用控制器的方法,並在那裏傳遞模型。這很好嗎?

我想在控制器中會有一個回調方法,當控制器安裝時會自動調用它。

+0

這裏回答你的問題。 http://stackoverflow.com/questions/27332840/how-to-access-ember-model-in-oninit-in-object-controller –

回答

2

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

只是簡單的模型,你不有做對控制器的任何設置這是可能的,這也將會給你的模型在控制器上。

+1

嗯。我明白你的意思了。換句話說。我所做的並不是錯的嗎? –

+0

如果你做了這件事情你沒有錯。 –

+0

聽起來很好,謝謝。 –

1

setupController鉤子方法將模型設置爲控制器的屬性。

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

您可以像控制器中的其他屬性一樣獲取模型。 this.get('model')

相關問題