Question

I have an ExtJs class that looks like this:

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

Now I get a string => str which contains the method name I need to run. I need to call the method in RuleExecutor specified by the string in str

The method is called correctly, but the arguments are not passed.

Like this:

//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);
}
Was it helpful?

Solution 2

Is this what you're looking for?

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

OTHER TIPS

Don't use 'arguments' as a variable name. There already is a built-in array-like object called 'arguments' in JavaScript. Your method may look like this:

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

I used the slice method from the 'real' array prototype. The line:

args = slice.call(arguments, 1)

copies all arguments except the first one to the args variable. You call RunRule like this:

RunRule("displayMessage", "Hello");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top