2

I'm creating an object dynamically and binding onclick event to it:

jQuery('<a/>', {
    click: function() { foo(arg1, arg2) },
    ...
})

Everything is working fine. The question is if it can be simplified so I don't need funciton() wrapper for calling foo function with arguments?

Thanks in advance.

2 Answers 2

3

You can't pass additional arguments to jQuery event handlers, jQuery passes the event object as the one argument to event handlers.

In jQuery 1.7 and up, the on() function allows you to extend the event object by passing an object containing the data you want to use inside your handler. You can access the data on the event.data object

function foo(event) {
    event.data.arg1;
    event.data.arg2;    
}

jQuery('<a/>').on('click', {arg1: val1, arg2: val2}, foo)
Sign up to request clarification or add additional context in comments.

2 Comments

the thing is i want my event handler to be a separate function so it can be utilised all over again.
Updated to show how you could use a reference to foo. You'll still need to construct the data object each time though you want to call foo, though.
2

The extra closure provided by the anonymous function is a necessary step — unless you can be certain of ECMAscript 5 support (IE8 and below don't), in which case you can use the bind method:

jQuery('<a/>', {
    click: foo.bind(this, arg1, arg2)
})

You can still use this method in IE8 and below if you're willing to include the Underscore micro-library, which contains a shim for bind:

jQuery('<a/>', {
    click: _.bind(foo, this, arg1, arg2)
})

If you can't do either of these, then you're out of luck!

2 Comments

nice but ie limitation is uncool. anyways, thank you for revealing this approach.
@Tim it turns out Underscore will do this. Amending my answer…

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.