从Extjs MVC应用程序中获取全局变量

Get global vars everywhere from Extjs MVC Application

本文关键字:获取 全局变量 应用程序 Extjs MVC      更新时间:2023-09-26

我正在学习ExtJs框架4.2.2 MVC,我想在Application.js中声明一个全局变量:

Ext.define('XApp.Application', {
    name: 'XApp',
    extend: 'Ext.app.Application',
    serverUrl: 'http://localhost:31109/',
    requires: [
        'XApp.util.Util',
        'XApp.util.SessionMonitor'
    ],
    views: [       
    ],
    controllers: [
       'Login',
       'Main',
       'Mail'
    ]
});

我想从任何地方得到serverUrl,因为将来我想改变服务器后端的这个url。在"应用程序"扩展类中,我找到了这个变量XApp.app.serverUrl但是在我的商店里,这种语法不起作用:

Ext.define('XApp.store.Xusers', {
    extend: 'Ext.data.Store',
    requires: [ 'XApp.model.Xuser'],
    model: 'XApp.model.Xuser',
    proxy: {
        type: 'jsonp',
        url: XApp.app.serverUrl + 'Login/Loadusers',
        reader: {
            type: 'json',
        }
    },
});

Firebug说: TypeError: XApp。App未定义

任何想法?

应用程序需要一些东西,这些东西最终需要XUsers存储。在这个时候,Ext的类管理器仍然是构建类等,还没有启动你的应用程序;这解释了你的未定义错误。

要解决这个问题,你可以在一个类方法中使用它,它必须在应用程序启动后被调用,例如在你的商店的构造函数中:
Ext.define('XApp.store.Xusers', {
    extend: 'Ext.data.Store',
    requires: [ 'XApp.model.Xuser'],
    model: 'XApp.model.Xuser',
    constructor: function() {
        this.proxy = {
            type: 'jsonp',
            url: XApp.app.serverUrl + 'Login/Loadusers',
            reader: {
                type: 'json',
            }
        };
        this.callParent(arguments);
    }
});

也就是说,根据您的用例,我认为我宁愿定义一个带有URL前缀的自定义代理,如:

Ext.define('XApp.data.proxy.DefaultJsonP', {
    extend: 'Ext.data.proxy.JsonP',
    alias: 'proxy.xjsonp',
    urlPrefix: 'http://localhost:31109/',
    reader: {
        type: 'json'
    },
    constructor: function() {
        // we want the config to have been applied beforehand this time
        this.callParent(arguments);
        this.url = this.urlPrefix + this.url;
    }
});