如何从静态 javascript 中获取对 ember/emberjs 中的视图实例的引用? [英] How to get a reference on a view instance in ember / emberjs from static javascript?
问题描述
我在网络(SOF 和 Google)上看到了很多关于此的问题,但到目前为止还没有明确的答案.
I have seen a lot of questions about that on the web (SOF and Google) but so far no clear answer to the issue.
我有一个带有各种视图和控制器的常用 Ember 应用程序.我的一个视图有一个实例方法,我想从静态上下文中调用它.因此在一个普通的 javascript 文件中.我应该获得对 ember 实例化的视图的引用以调用该方法吗?
I have a usual Ember application with various views and controllers. One of my views has an instance method that I would like to call from a static context. Thus in a normal javascript file. I should I get a reference to the view instanciated by ember to call the method on ?
几行代码来说明我的问题:
A few lines of code to illustrate my issue :
在 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();
}
};
推荐答案
这是我个人解决这个问题的方法.我正在使用 Ember.View 的didInsertElement"在中央位置注册视图.这适用于单例视图.对于非单一视图,必须开发更复杂的 ViewRegistry.
This is my personal approach to this problem. I am using the "didInsertElement" of Ember.View to register the View in a central place. This works well for singleton views. For non-singleton views, one would have to develop a more sophisticated 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();
}
};
这篇关于如何从静态 javascript 中获取对 ember/emberjs 中的视图实例的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!