JQuery: more on events
In the previous post, we’ve met the bind method and saw how it can be used to simplify the code needed for event hookup. One of the questions you’ve might ask is how do you “unsubscribe” from a specific event. And yes, JQuery does introduce a method for doing that: it’s called…unbind. What a big surprise, right?
You’ve got several options here. If you call this method and pass no argument, then you’ll be removing all existing event hookups from the wrapped set. Take a look at the following code:
$("#bt").bind("click mouseover", "howdy", function(evt) {
alert(evt.data);
$(this).unbind();});
This is a really interesting example…As you can see, we’re passing the same anonymous function and we’re hooking it up for the click and mouseover events. In the body of that function we’re calling the unbind method over a new JQuery object which wraps the “current” node responsible for the event. Since we’re not passing any parameters, all previous event hookups will be eliminated. In practice, this means that we’ll only see the alert once because we’re removing all event handlers from within the method that handles those events.
There’s also the option of passing an event name. For instance, say that we' replace the previous unbind call with the following method invocation:
$(this).unbind("mouseover");
With this call, you’ll just be removing the mouseover hookups: whenever you click over the button you’ll still get the alert.
There’s still one more option here: you can remove a single function from the list associated with an event. In order to do that, you can’t use anonymous functions though. Here’s a quick example that shows how this feature works:
<input type="button" value="wrap items" id="bt" />
<input type="button" value="cancel bind" id="cancel" />
<script type="text/javascript">
function sayHiOnce() {
alert("Hi once!");
}
$(function() {
$("#bt").bind("click", sayHiOnce);
$("#cancel").bind("click", function() {
$("#bt").unbind("click", sayHiOnce);
});
});
</script>
As you can see, you do have some granularity for unbinding events. There’s still one more interesting option, but I’ll leave it for a future post. Keep tuned for more on JQuery.