Saturday, October 5, 2013

Handling Global Variables in Ext JS

Classes don't exist in JavaScript but Ext JS does a fine job in emulating classes as found in object oriented programming languages. This means everything in Ext JS is a class and these classes mostly fall in either of these categories; Model, View, Controller, and Store. So if you could map any new class to either of these category, things fall in place nicely. Now what if something don't fall in either of these ?

What if you need to move common labels and constants to a separate class. If you are writing plain JavaScript then it's quite trivial but NOT so obvious in Ext JS. Let's figure out how to handle labels or common variables in Ext JS.

Singleton Class

Ext JS has support for singleton classes. By definition, singleton can't be instantiated more than once. Global or common variables can be created using a singleton class.

     Ext.define("App.Constants", {
             singleton  : true,  
             
             BASE_URL : "http://localhost:8080/",
             LABLE_HEADER : "geekrai.blogspot",
             TIMEOUT : 6000
     });

Please, note that, singleton property is set to true. That's all we need to do to convert a class into a singleton class. You can test if it's indeed a singleton by creating an instance of above class :

      Ext.create("App.Constants"); //Throws error

Global variables are added in class as key value pair. Save above content in file Constants.js. File can be created at same level as other packages like model, view etc.

Accessing Constants in Application

Above class needs to get loaded in application to successfully access properties mentioned above. As it holds some of the global variables so ideal place will be to load it inside app.js.

     Ext.application({  
           // include model, view, controller etc.

           requires: ['App.Constants']

     });

Now we are good to access variables in any class as App.Constants.<KEY>.
console.log(App.Constants.TIMEOUT);


*** You can also use Ext JS singleton to create utility classes. 

No comments:

Post a Comment