Corentin
Corentin

Reputation: 387

jQuery function as a string with arguments as Array (JavaScript "apply()" equivalent for jQuery elements)

I would like to call a jQuery function into a jQuery plugin, with its name as a string, and its arguments as an object (Array). I'm looking for a kind of equivalent to the JavaScript "apply" function in jQuery.

I had to find a workaround, but it's really dirty and limited. Here it is :

//funcName is the name of the function I want to call
//funcArgs is an Array of arguments
//$(this) is a jQuery element
switch(funcArgs.length) {
    case 1:
        $.fn[funcName] && $(this)[funcName](funcArgs[0]);
        break;
    case 2:
        $.fn[funcName] && $(this)[funcName](funcArgs[0], funcArgs[1]);
        break;
    //...
    default:
        $.fn[funcName] && $(this)[funcName]();
}

Could you please help me to make it unlimited ? (Without any switch...)

Thank you very much,

Upvotes: 1

Views: 513

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075169

jQuery is a library, not a language. The language you're using is JavaScript, and so apply is exactly what you want:

var $this = $(this);
$this[funcName].apply($this, funcArgs);

Or

$.fn[funcName].apply($(this), funcArgs);

...since $.fn is the prototype underlying jQuery instances.

Upvotes: 3

Related Questions