Search code examples
jquerycallapplydispatch

Can I call jQuery method with given selector, method name and variable arguments?


I tried to find the way through web search, but I could not.

What I want to do is dispatching jQuery method like below;

var dispatchFunction = function (selector, jQueryMethod, jQueryArgs) {
    jQuery(selector)[jQueryMethod].apply(this, jQueryArgs);
}

Although It looks like the result of

jQuery("#id")["methodName"]

is a function. But when I call 'apply' to that function in javascript console, it does not work like below;

func = jQuery("#todo")["text"];
=> function (e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)}

jQuery("#todo")["text"]();
=> "abc"

func.apply(this);
=> ""

func.apply(this, []);
=> ""

Is there any way to do this?


Solution

  • What you need to do is:

    var dispatchFunction = function (selector, jQueryMethod, jQueryArgs) {
        var selection = jQuery(selector);
        selection[jQueryMethod].apply(selection, jQueryArgs);
    }
    

    You might want to read more info about this keyword and function vs method calls in JS.