繁体   English   中英

动态调用extjs类中的函数

[英]call function in extjs class dynamically

我有一个ExtJs类,看起来像这样:

Ext.define("RuleExecutor", {
    singleton: true,
    displayMessage: function(msg) {
        Ext.Msg.alert('Popup Message', msg[0]);
    },
    disableById: function(field) {
        Ext.getCmp(field).setDisabled(true);
    },
    //more functions are here...
});

现在,我得到一个字符串=> str ,其中包含我需要运行的方法名称。 我需要在str中的字符串指定的 RuleExecutor中调用方法

该方法已正确调用 ,但未传递参数。

像这样:

//arguments is an array
function RunRule(str, arguments) {
  //I tried this....
  var fn = RuleExecutor[str];
  fn(arguments)

  //This doesn't work either..
  RuleExecutor[str].apply(this, arguments);
}

不要使用“参数”作为变量名。 JavaScript中已经有一个内置的类似数组的对象,称为“ arguments ”。 您的方法可能如下所示:

function RunRule(str) {
    var slice = Array.prototype.slice,
        args = slice.call(arguments, 1);
    RuleExecutor[str].apply(RuleExecutor, args);
}

我使用了“真实”数组原型中的slice方法。 该行:

args = slice.call(arguments, 1)

将除第一个参数以外的所有参数复制到args变量。 您可以这样调用RunRule

RunRule("displayMessage", "Hello");

这是您要找的东西吗?

Ext.onReady(function () {
    Ext.define("RuleExecutor", {
        singleton: true,
        displayMessage: function (msg) {
            Ext.Msg.alert('Popup Message', msg[0]);
        },
        disableById: function (field) {
            Ext.getCmp(field).setDisabled(true);
        }
    });

    var str = 'displayMessage';
    RuleExecutor[str](['bar']);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM