1

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,

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

My post was not clear enough. I know jQuery is a library and JavaScript a language, but I didn't know how to use "apply" with it. You perfectly answered me! Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.