Ext JS Globals

Sencha

I realize many programmers cringe when talking about global functions and variables. This discussion gets even greater when dealing with JavaScript since we all know JavaScript will overwrite all variables regardless of what you originally assigned it as. Ergo a variable belonging to a function can easily be re-written by a number or string.

This argument doesn’t change the need for having some things defined globally. Sometimes there are timers created for action on one page that suddenly need to be stopped as you navigate the application. You will also need to restart the timer when returning to the page.

Let us not forget a setting such as a teamId. This value is used on multiple tables and determined when logging into the website or even passed when visiting the website. In either case it does need to be available throughout the site and it is cumbersome to continually code to get the value.

There are other options you can include session storage, browser session storage, browser local storage, etc. Each has their own set of challenges in obtaining the stored information. Technology presents different challenges also. Then there is any kind of storage you choose can be overwritten by another function so even with those solutions you don’t have a sure way to keep global values 100% safe from unwanted/unplanned changes. This relies on the programmer(s) working on the project understanding the use of anything stored. Often, unfortunately programmers get sloppy.

An extremely popular question I encounter with Ext JS is how to work with global variables. So yes, there are others who use them beside myself. They are valuable and quite usable when taking care and commenting code properly.

Here is an example how you can use global values in Ext JS

Simply create a new such as globalFunctions.js.

Ext.define('globalFunctions', {
    // Singleton is a popular design pattern in OO languages where a class configured
    // to be singleton has only one instance throughout the application.
    // Configured as singleton, an instance is automatically created.
    // Ext.create('globalFunctions') would generate an instantiation error
    singleton: true,
    // Allows us to call this class without using the full name spec in more
    // controlled production environments
    alternateClassName: 'globalUtils',

    // config lets us define variables with access from this class
    // doing so creates both getter and setter for the variable
    config: {
        userName: 'Andy Allord - Sencha MVP',
    },

    constructor: function (config) {
        this.initConfig(config);    // Initialize config to make variables available
        this.callParent([config]);  // Initialize on parent
    },

    changeUserName: function () {
        // For demo this is self contained. In a production environment it is best
        // to place the dialog definition into a separate file.
        let wdw = Ext.create('Ext.Dialog', {
            title: 'Change User Name',
            padding: 10,
            width: 400,
            height: 200,
            bbar: [{
                xtype: 'button',
                text: 'Change Name',
                iconCls: 'x-fa fa-save',
                handler: function (btn) {
                    // Uses global setter to set userName global variable
                    globalUtils.setUserName(wdw.query('#tfNewUserName')[0].getValue());
                    Ext.ComponentQuery.query('#dfGlobalVar')[0].setValue(globalUtils.getUserName());
                    btn.up('dialog').close();
                }
            }, {
                xtype: 'button',
                text: 'Cancel',
                iconCls: 'x-fa fa-ban',
                handler: function () {
                    wdw.close();
                }
            }],
            items: [{
                xtype: 'textfield',
                itemId: 'tfNewUserName',
                label: 'New User Name',
                anchor: '100%'
            }]
        });
        wdw.show();
        Ext.ComponentQuery.query('#tfNewUserName')[0].focus();
    },

    getTestAve: function () {
        let tot = 0;
        // Uses the arguments array so any number of test scores can be sent
        for (let x = 0; x < arguments.length; x++) {
            tot += arguments[x];
        }
        // Format number to 2 decimal places in the returned result
        return Ext.util.Format.number(tot / arguments.length, '0.00');
    }
});

Once you’ve created this file, from here it is simply requiring the your newly defined global inside your application.

Ext.application({
    name : 'Fiddle',

    requires: [
        'globalFunctions'
    ],

    launch : function() {
        let pnl = Ext.create('Ext.Panel', {
            padding: 10,
            items: [{
                xtype: 'displayfield',
                itemId: 'dfGlobalVar',
                label: 'Global Variable userName',
                // Use global getter for defined variable userName
                value: globalUtils.getUserName()
            }, {
                xtype: 'displayfield',
                label: 'Calculated Test Average getTestAve(100, 84, 73, 93, 64, 53, 31)',
                // Send to global function to set the value of this display field
                value: globalUtils.getTestAve(100, 84, 73, 93, 64, 53, 31)
            }, {
                xtype: 'button',
                text: 'Change User Name',
                iconCls: 'x-fa fa-plus',
                handler: function () {
                    globalUtils.changeUserName();
                }
            }, {
                xtype: 'button',
                text: 'Get User Name',
                iconCls: 'x-fa fa-arrow-down',
                handler: function () {
                    Ext.Msg.alert('Global User Name', 'User Name: ' + globalUtils.getUserName());
                }
            }, {
                xtype: 'displayfield',
                margin: '20 0 0 0',
                label: 'Demonstrated by Andy Allord - Sencha MVP'
            }]
        });
        Ext.Viewport.add(pnl);
    }
});

You can the access the functions and/or variables using the defined namespace in your globalFunctions.js file.

Using Ext JS this is just as good of a way to handle values and functions used throughout your Ext JS applications.

Author: aallord

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.