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

时间:2019-01-08 12:53:55

标签: extjs extjs4.2

我尝试声明 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. 还有其他方法可以声明全局变量吗?

1 个答案:

答案 0 :(得分:2)

是的,您可以在Extjs中为您的应用程序使用singleton类。在创建Utilities时,需要在内部设置config singleton:true。将其设置为true时,该类将被实例化为单例。例如:

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

Logger.log('Hello');

您可以在这里查看Sencha fiddle演示示例。这只是您可以在应用程序中实现的小演示。您也可以在这里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()
        });
    }
});