Where to add Global variables in ExtJS MVC?

一世执手 提交于 2019-12-21 09:28:31

问题


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?


回答1:


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.




回答2:


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




回答3:


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



回答4:


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

    });

})();


来源:https://stackoverflow.com/questions/13865251/where-to-add-global-variables-in-extjs-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!