【问题标题】:How to get any controller instance from init() method of a view?如何从视图的 init() 方法中获取任何控制器实例?
【发布时间】:2013-02-26 12:57:19
【问题描述】:

我正在从旧版本的 EmberJS 迁移我的项目。在某些地方,我曾经通过在任何视图的 init() 方法中使用以下方法来获取与视图无关的控制器实例:

var controller = App.get('router').get('firstController');

但是现在这会引发以下错误。

  Uncaught TypeError: Cannot call method 'get' of undefined 

这可能是因为它无法获取Router对象。现在如何获取与视图无关的控制器实例?或者如何获取路由器对象

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    “需要”功能允许控制器访问其他控制器,这允许控制器的视图访问其他控制器。 (Ember 中对需求的一个很好的解释:http://darthdeus.github.com/blog/2013/01/27/controllers-needs-explained/

    正如Cannot access Controller in init function of View in 1.0.0rc 中所解释的,当调用init() 时,视图的controller 属性尚未设置,因此您需要在视图生命周期的稍后时间访问controller。例如,这可能是 willInsertElement()didInsertElement() 挂钩。

    下面是一个示例,展示了使用需要从视图访问另一个控制器:

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

    【讨论】:

    • 谢谢..它有效...但我想知道删除获取路由器对象并允许这样做的座右铭是什么...我看到它的方式,如果我在needs 中拥有所有控制器它将工作相同..我可能是错的..以前它只是引用..现在一个额外的数组...
    • @CodeJack 这里有一个很好的解释:stackoverflow.com/questions/14166995/…
    • 谢谢...现在我觉得我也必须重构代码...而不仅仅是升级:)
    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 2015-07-25
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多