Thursday, October 29, 2009

JQuery pass parameter to event handler

How can you pass values into a event handler, plain and simple?

here it is!

var somevar = 'value'; //declare some var

And here comes the magic, on the bind function, in the second parameter, you define the data structure to pass on to your anonymous event handler (which can be multiple parameters, comma separated).
(notice that you have to receive the event parameter on the handler function, so you can access the data you sent)

$("something").bind("click", { data: somevar }, function(event) {
event.data.data //this is the way you can access it on the handler function
}

So, what's the use of this? you can send data that is accessible in your current context, where you are defining the handler, but inside the handler it's unreachable.

Hope this is as useful for you as it was for me!

See you soon :)

No comments: