How to call jQuery plugins using the apply() or call() functions
This short post shows how to set the right context for jQuery plugins.
apply() function is especially useful, if you want to call functions with dynamically generated parameters.
The first argument of
call() becomes the
this value of the called function.
this in the scope of a jQuery plugin is the jQuery element it was called on, the call of a plugin looks like this:
var $el = $('#anyElement'); $el.jQPlugin.apply($el, arrayOfArgs); $el.jQPlugin.apply($el, arg[, ...]);
$el is cached to avoid double selection. This of course only works, if
jQPlugin accepts the arguments in the
Typeahead.js for example accepts a variable number of arguments.