1

Suppose we need to dynamically construct plugin calls such as

$('#myDiv').myPlugin({a:'a',b:'b'});

will be something like:

function funcCallBuilder(selector, func, opts){
  //dynamically construct plugin call here
}

using:

funcCallBuilder('#myDiv', 'myPlugin', {a:'a',b:'b'});

Can someone point out the correct way of doing this?

0

1 Answer 1

4

Not sure if I really understand the question, but if you simply want your first and third code snippet to have the same effect, just use apply:

function funcCallBuilder(selector, func, opts){
    func.apply($(selector), [opts]);
}

or, if you really want to pass the function as a string instead of a function object (not much point IMHO):

function funcCallBuilder(selector, func, opts){
    $.fn[func].apply($(selector), [opts]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

yep, .apply( ) should do it for you. Although, I think it should be $.fn[func].apply( $(selector), opts );
$.fn[func].apply($(selector), opts); worked for me! Thank you so much Tgr.
Should have used call or arrayified the argument; fixed now. If you are sure you only need one argument, the simpler syntax $(selector)[func](opts) should work too.

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.