“需要”功能允许控制器访问其他控制器,这允许控制器的视图访问其他控制器。(Ember 中需求的一个很好的解释:http: //darthdeus.github.com/blog/2013/01/27/controllers-needs-explained/)
如1.0.0rc 中 View 的 init 函数中无法访问 Controller 中所述,视图的controller
属性在调用时尚未设置init()
,因此您需要controller
在视图生命周期的稍后时间访问。例如,这可能是willInsertElement()
ordidInsertElement()
钩子。
这是一个示例,演示使用需要从视图访问另一个控制器:
http://jsbin.com/ixupad/186/edit
App = Ember.Application.create({});
App.ApplicationController = Ember.Controller.extend({
doSomething: function(message) {
console.log(message);
}
});
App.IndexView = Ember.View.extend({
templateName: 'index',
init: function() {
this._super();
// doesn't work, controller is not set for this view yet see:
// https://stackoverflow.com/questions/15272318/cannot-access-controller-in-init-function-of-view-in-1-0-0rc
//this.get('controller.controllers.application').doSomething("from view init");
},
willInsertElement: function() {
this.get('controller.controllers.application').doSomething("from view willInsertElement");
},
clickMe: function() {
this.get('controller.controllers.application').doSomething("from clickMe");
}
});
App.IndexController = Ember.Controller.extend({
needs: ['application']
});