【问题标题】:How to get a reference on a view instance in ember / emberjs from static javascript?如何从静态 javascript 获取 ember / emberjs 中视图实例的引用?
【发布时间】:2013-02-13 12:41:53
【问题描述】:

我在网络(SOF 和 Google)上看到了很多关于此的问题,但到目前为止还没有明确的答案。

我有一个带有各种视图和控制器的常用 Ember 应用程序。我的一个观点有一个我想从静态上下文中调用的实例方法。因此在一个普通的 javascript 文件中。我应该获得对 ember 实例化的视图的引用以调用该方法吗?

几行代码来说明我的问题:

在 ApplicationView.js 中:

App.ApplicationView = Em.View.extend({
    templateName: 'application',

    myInstanceMethod:function () {
       this.anotherInstanceMethod(some, params);
    },
    // ... more code
});

在 MyUtils.js 中:

var myUtils = myUtils || {
    myMethod: function() {
        myApplicationViewInstance.myInstanceMethod();
    }
};

【问题讨论】:

    标签: view reference ember.js


    【解决方案1】:

    这是我个人解决这个问题的方法。我正在使用 Ember.View 的“didInsertElement”在中心位置注册视图。这适用于单例视图。对于非单例视图,必须开发更复杂的 ViewRegistry。

    灰烬部分

    var App = Ember.Application.create({
        viewRegistry : {
            applicationView : null
        },
    });
    
    App.ApplicationView = Ember.View.extend({
        templateName : 'application',
        didInsertElement : function(){
            App.set("viewRegistry.applicationView", this);
        }
    });
    

    在 MyUtils.js 中:

    var myUtils = myUtils || {
        myMethod: function() {
            App.get("viewRegistry.applicationView").myInstanceMethod();
        }
    };
    

    【讨论】:

    • 不错的收获。我发现,当我在路由器中注册了我的 applicationController 时,我可以像使用注册表一样通过 App.get('router.applicationView') 访问我的 applicationView!谢谢
    【解决方案2】:

    Ember 已经有一个“全局视图哈希”

    ember.js 中搜索Ember.View.views = {}

    它由每个视图的元素 id 索引,因此获取视图很简单:

    myView = Ember.View.views[$('.myViewSelector').attr('id')]
    

    然而,我的导师认为使用这种方法是一种肮脏的技巧,并建议我找到更好的方法。他写了一个测试助手:

    window.lookupView = function(key) {
      var activeViews = app.__container__.lookup('router:main')._activeViews;
      if(!activeViews) { throw new Error("No active views."); }
      if(!activeViews[key]) { throw new Error("No view '%@'.".fmt(key)); }
      return activeViews[key][0];
    };
    

    我用来获得我想要的 parentView,然后是 parentView.get('childViews') 的任何孩子

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    相关资源
    最近更新 更多