3

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?

6
  • there is a simple solution is by using event data, however you have to change the test function prototype. Commented Jun 10, 2014 at 8:04
  • 1
    Depends. Will test() eventually be used to directly handle the click event? Commented Jun 10, 2014 at 8:15
  • @Jack ah yes, if it's not, we can use an anonymouse function like function(e){} and then access the e.data to get the arguments for the test function called inside. Commented Jun 10, 2014 at 8:17
  • One more question. How can I release bind from #btn ? Commented Jun 10, 2014 at 8:19
  • @Niezbor You mean unbind()? Though, on() and off() are preferable (according to docs). Commented Jun 10, 2014 at 8:20

3 Answers 3

4

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)));
Sign up to request clarification or add additional context in comments.

3 Comments

Why first of argument in apply is null?
@Niezbor First argument decides what is this in the function, in op's case, it doesn't matter.
@Niezbor the explanation of xdazz is enough, in fact my explanation was a bit wrong about the this keyword, you can still use the this keyword in your function but it will refer to some outer context, such as the window object.
1

Make a closure.

$('#btn').bind("click", function() { test('Hello', 'my', 'world'); });

or

$('#btn').bind("click", function() { test.apply(null, array); });

Comments

1

jsFiddle Demo

You could use apply to accomplish that.

$("#btn").bind("click", function(){ test.apply({},array)});

Comments

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.