user1011792
user1011792

Reputation:

JQuery unpack array of parameters

I'm using typeahead typeahead as following:

$('my_elements').typeahead(options, dataset1, dataset2, ...). However number of datasets is dynamic, and I have them calculated and stored in an array(along with options). So how to pass the array as the arguments list? I tried using javascript apply function:

 $('my_elements').each(function(){
   typeahead.apply(this, params_array);
 });

But an error is genereated: typeahead is not defined! So how to use apply function on the result of jquery selector ?

Upvotes: 1

Views: 318

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

When you try to access typeahead directly, it tries to find a reference with that name in the current scope or in a ancestor scope.

But since typeahead is a plugin it is a property of the jQuery prototype object, so you need to access it via $.fn.typeahead.

Another pointed to be noted is this inside the plugin should refer to jQuery object not dom element so

$('my_elements').each(function () {
    $.fn.typeahead.apply($(this), params_array);
});

or

$.fn.typeahead.apply($('my_elements'), params_array);

Upvotes: 1

Related Questions