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
?
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
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.
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
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); }
});
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With