如何在EXTJS中使用全局函数/实用程序类

Kav*_*taC 2 extjs global-variables

我的代码结构如下 - >

MyApp-> app - > controller,model,store,shared(util-> Utility.js),view

我创建了以下实用工具类

Ext.define('MyApp.shared.util.Utilities', {

    myFunction : function (val, meta, rec) {
        //do something 
        return val;
    }
});
Run Code Online (Sandbox Code Playgroud)

我试图在我的网格中渲染列时调用myFunction,如下所示 - >

Ext.define('MyApp.view.MyGrid', {
        extend: 'Ext.grid.Panel',        

        initComponent: function() {
            var rendererFn = Ext.create('MyApp.shared.util.Utilities');

            this.columns = [{
                text: 'Col1',
                dataIndex: 'col1'
                renderer: rendererFn.myFunction
            };

            this.store = new MyApp.store.MyStore();
            this.store.load();
            this.callParent(arguments);
        }        
});
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我想知道这是否是使用全局函数的正确方法.

Eva*_*oli 8

更好的方法是将您的类声明为单例:

Ext.define('MyApp.shared.util.Utilities', {
    singleton: true,
    myFunction : function (val, meta, rec) {
        //do something 
        return val;
    }
});

Ext.define('MyApp.view.MyGrid', {
    extend: 'Ext.grid.Panel',        

    initComponent: function() {
        this.columns = [{
            text: 'Col1',
            dataIndex: 'col1'
            renderer: MyApp.shared.util.Utilities.myFunction
        }];

        this.store = new MyApp.store.MyStore();
        this.store.load();
        this.callParent(arguments);
    }        
});
Run Code Online (Sandbox Code Playgroud)