javascript 我应该在哪里定义 ExtJS 4 MVC 中的全局函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9261458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where should I define global functions in ExtJS 4 MVC?
提问by Julian Hollmann
I need to define some functions which i can call everywhere in my app. What is the best approach to achieve this?
我需要定义一些可以在我的应用程序中随处调用的函数。实现这一目标的最佳方法是什么?
回答by David Kanarek
Personally, to keep it as EXT-MVC as possible, I have a Utilities class full of static methods. This can be required like any other class to maintain proper dependency relations. This also ensures that the methods are run in an EXT environment, so all of EXT is available.
就个人而言,为了尽可能保持 EXT-MVC,我有一个充满静态方法的 Utilities 类。这可以像任何其他类一样需要以维护适当的依赖关系。这也确保方法在 EXT 环境中运行,因此所有 EXT 都可用。
Ext.define('MyApp.Utilities', {
statics: {
foo: function (a, b) {
return a + b;
}
}
});
Ext.define('MyApp.MyView', {
extends: 'Ext.panel.Panel',
requires: ['MyApp.Utilities'],
initComponent: function () {
MyApp.Utilities.foo(1, 2);
}
});
回答by gm2008
An alternative way other than @David Kanarek's statics approach is to define a singleton. Codes:
除了@David Kanarek 的静态方法之外,另一种方法是定义一个单例。代码:
Ext.define('MyApp.Utilities2', {
singleton: true,
global_var2: 'Hello World',
foo2: function (a, b) {
return a + b;
},
});
I've created a fiddle here: https://fiddle.sencha.com/#fiddle/qu1
我在这里创建了一个小提琴:https: //fiddle.sencha.com/#fiddle/qu1
The difference between the statics and singleton approach is that
静态方法和单例方法之间的区别在于
- MyApp.Utilities2 (singleton approach) is an object,
- MyApp.Utilities (statics approach) is a class.
- MyApp.Utilities2(单例方法)是一个对象,
- MyApp.Utilities(静态方法)是一个类。
So It's up to you whether to reference the class itself or to reference one instance of that class for convenience.
因此,为方便起见,是引用类本身还是引用该类的一个实例取决于您。