JQuery: triggering events
[I’ve updated the text for JQuery 1.3]
In the previous post we’ve seen that JQuery introduces a couple of methods which reduce the code you need to write to handle events. At the time, we’ve seen that calling those methods without parameters would result in invoking the handlers associated with that event. Now, as you’re probably wondering, there’s also a general way of achieving that which will even let you do the same for the events that don’t have a specific shortcut method: I’m talking about the trigger method.
Take a look at the following code:
$("#bt").click(function() { alert("hi2"); });
$("#cancel").click(function() { $("#bt").trigger("click"); });
As you can see, we’re using an anonymous function to handle the #bt’s click event. Now take a look at the anonymous method that handles the click event for the #cancel button…in that case, we’re getting a reference to a JQuery object that wraps the #bt button and we’re “triggering” the click event. Notice that we’re not really generating the event (keep this in mind when we talk about event propagation in future posts)…to be honest, we’ll only be executing all the functions that handle the event.
Notice that from v1.3 onwards, you’ll get bubbling when you call the trigger method.
I guess that you can see this as way to stop introducing global named functions because you could always add named functions and call them directly instead of using JQuery’s trigger method. I guess that it’s all for today! Keep tuned for more on JQuery.