Reputation: 1857
I would like to bind to the element function, which take several arguments. How to do it right?
For example, I have function:
function test(arg1, arg2, arg3) {
console.log("arg1:", arg1);
console.log("arg2:", arg2);
console.log("arg3:", arg3);
}
and I would like to bind this to element with ID #btn
, but all arguments are in array:
var array = ['Hello', ' my', ' world!'];
How can I do this? I will try something like this:
$("#btn").bind("click", array, test);
Any suggestions?
Upvotes: 3
Views: 762
Reputation: 160853
You could do like below:
var array = ['Hello', ' my', ' world!'];
$("#btn").bind("click", function() {
test.apply(null, array);
});
Or using $.proxy
method to add the arguments by:
$("#btn").bind("click", $.proxy.apply($.proxy, [test, null].concat(array)));
Upvotes: 4
Reputation: 82287
You could use apply
to accomplish that.
$("#btn").bind("click", function(){ test.apply({},array)});
Upvotes: 1
Reputation: 198324
Make a closure.
$('#btn').bind("click", function() { test('Hello', 'my', 'world'); });
or
$('#btn').bind("click", function() { test.apply(null, array); });
Upvotes: 1