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?

share|improve this question

62% accept rate
good question+1 – AlexanderN May 16 '11 at 21:52
feedback

1 Answer

up vote 3 down vote accepted

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]);
}
share|improve this answer
yep, .apply( ) should do it for you. Although, I think it should be $.fn[func].apply( $(selector), opts ); – KOGI Feb 17 '11 at 18:17
$.fn[func].apply($(selector), opts); worked for me! Thank you so much Tgr. – Sam3k Feb 17 '11 at 20:17
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. – Tgr Feb 18 '11 at 11:15
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.