首页 > 解决方案 > 有没有其他方法可以在 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. 有没有其他方法来声明全局变量?

标签: extjsextjs4.2

解决方案


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

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

Logger.log('Hello');

您可以在此处查看正在运行的Sencha fiddle演示。这只是你可以用你的应用程序实现的小演示。你也可以在这里访问ExtJS gitlab 项目与 sigletone 类实用程序

代码片段

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()
        });
    }
});

推荐阅读