如何在 EXTJS 中使用全局 functions/Utility Class

How to use global functions/Utility Class in EXTJS

我的代码结构如下->

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

我创建了以下实用程序Class

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

    myFunction : function (val, meta, rec) {
        //do something 
        return val;
    }
});

我在网格中渲染列时尝试调用 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);
        }        
});

这很好用,但我想知道这是否是使用全局函数的正确方法。

更好的方法是将您的 class 声明为单身人士:

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