有没有其他方法可以在 Extjs 中声明全局变量?

Is there any other way to declare global variable in Extjs?

我尝试在 ExtJs4.2 版本中声明全局变量,如下所示。

Ext.application({
    globals: {
        praticalsValue: []
    },
    requires: ['MyApp.util.Utilities'] //Don't forget to require your class
});
  1. 我遇到的问题是出现控制台错误

    http://localhost:8080/sample-webapp/MyApp/util/Utilities.js?_dc=1546951098727 net::ERR_ABORTED 404(未找到)

  2. 还有其他声明全局变量的方法吗?

是的,您可以在 Extjs 中为您的应用程序使用 singleton class。当你创建你的 Utilities 所以里面你需要设置 config singleton:true 当设置为 true 时, class 将被实例化为单例。例如:

Ext.define('Logger', {
    singleton: true,
    log: function(msg) {
        console.log(msg);
    }
});

Logger.log('Hello');

你可以在这里查看工作Sencha fiddle demo. It's just small demo you can implement with your application. And also you can visit here ExtJS gitlab project with sigletone class utility

代码段

Ext.application({
    name: 'Fiddle',

    launch: function () {

        //This sigletone class will accesible througout the app via using the
        //Name {AppConstants( whatever name your provide you can access with the same name)}

        //{singleton: true,} When set to true, the class will be instantiated as singleton.
        Ext.define('AppConstants', {
            alternateClassName: 'AppConstants',
            singleton: true,

            config: {
                userId: '1'
            },

            constructor: function (config) {
                this.initConfig(config);
            }
        });

        Ext.create('Ext.panel.Panel',{

            title: 'Define global variable in singletone class',

            bodyPadding: 15,

            items: [{
                xtype: 'button',
                text: 'Set value userId',
                margin: '0 15',
                handler: function () {

                    //we set value using setter of singleton.
                    Ext.Msg.prompt('New value of userId', 'Please enter userId value', function (btn, text) {
                        if (btn == 'ok') {
                            AppConstants.setUserId(text);
                        }
                    });
                }
            }, {
                xtype: 'button',
                text: 'Get value userId',
                handler: function () {
                    //we get value using getter of singleton.
                    Ext.Msg.alert('userId value is ', AppConstants.getUserId());
                }
            }],

            renderTo: Ext.getBody()
        });
    }
});