R9102
R9102

Reputation: 727

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

I tried declaring global variable in ExtJs4.2 version as shown below.

Ext.application({
    globals: {
        praticalsValue: []
    },
    requires: ['MyApp.util.Utilities'] //Don't forget to require your class
});
  1. issue I am facing is getting console error

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

  2. Is there any other way to declare global variable?

Upvotes: 2

Views: 447

Answers (1)

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

Yes, You could use singleton class in Extjs for you application. When you creating your Utilities so inside that you need to set config singleton:true When set to true, the class will be instantiated as singleton. For example:

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

Logger.log('Hello');

You can check here with working 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

Code Snippet

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

Upvotes: 2

Related Questions