JQuery: one-shot event handlers
In the previous posts, we’ve started looking at how you can use JQuery to simplify event handling. As we’ve seen, we can use the bind method to hook up a method as an event handler. When we’re no longer interested in receiving more notifications, we can always call the unbind method to “unsubscribe” ~from that event.
There are several times where we’re only interested in handling the event for the first time. We already know how to do that (by using unbind through the function that is called when the event is raised), but JQuery simplifies things a bit by introducing the one method. Here’s how you’d hookup a method for a one time event handling:
$("#bt").one("click", function() {alert("hi"); })
.bind("click", function() { alert("hi2"); });
Internally, JQuery hooks up everything and then removes the binding so that future events won’t result in having the method executed again. Running the previous snippet produces the same result as the one we saw in the previous post. If you look at the docs, you’ll notice that the behavior is really similar to the one we’ve seen for bind. And that’s all for today. There’s still more to come on JQuery. Stay tuned!