Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to add Global variables in ExtJS MVC?

I am wondering where to add global variables for an ExtJS Application. I already looked at some suggestions in stackoverflow that mention that you can add them inside app.js. But, can anyone be more specific? My app.js looks something like this:

Ext.application({

    launch: function() {..}

});

So, where exactly do the variables go? In the launch function? Outside Ext.application?

like image 928
Art F Avatar asked Dec 13 '12 17:12

Art F


4 Answers

Better approach would be to create a separate class to hold such global constants. Then you should just put that constants class as requires in app.js.

Ext.define("App.Constants", {
         singleton  : true,   

         BASE_URL : "http://localhost:8080/",
         LABLE_HEADER : "geekrai.blogspot",
         TIMEOUT : 6000 
 });

This will ensure that class is loaded and now you can access any property/global value. I have mentioned the same in detail on my blog : link

like image 155
rai.skumar Avatar answered Nov 13 '22 18:11

rai.skumar


Declare your own object namespace and add them there:

Ext.ns('My.Application.Globals');

My.Application.Globals.SomeValue = 5;
My.Application.Globals.SomeText = 'Hello World!';

However globals are usually frowned upon unless absolutely needed, so try and get around using them if you can.

like image 27
Lloyd Avatar answered Nov 13 '22 20:11

Lloyd


I know you already accepted an answer which is fine. I just wanted to add an MVC way to include namespaced variables available to the app. There is one caveat to these 'globals' - you can not use them in your class definitions. Meaning you can not reference your app in Ext.define({}) methods. They have to be use in initComponent method or later.

So here is what I do:

Ext.application({
    name:'MyApp',
    appFolder:'js/app',
    controllers:[ 'Main' ],
    autoCreateViewport : true,
    launch:function () {
        console.log("App Launched!");
        MyApp.app = this;   //added this to get reference to app instance. IMPORTANT!    
    }, 
    //variables used throughout the app
    globals:{
        myURL:'http://example.com',
        magicNum:5
    }
});

To use these application wide variables you reference your app namespace and so do not pollute the global space. Like this:

MyApp.app.gloabals.magicNum
like image 4
dbrin Avatar answered Nov 13 '22 18:11

dbrin


Aside from whatever features may be built into Ext, you can always use an immediate function to create a closure:

(function(){
    var globalVariable = 'foo';    

    Ext.application({

        launch: function() { alert(globalVariable); }

    });

})();
like image 3
Adam Rackis Avatar answered Nov 13 '22 19:11

Adam Rackis