Blog Archives

A bindOnce event listener for Backbone.js

I’m going to guess you are familiar with Backbone, the MVC framework of choice for many web developers. I use Backbone a fair amount for its Model and Event aspects both because it works and it’s often what others expect.

But there is one feature I miss with Backbone event handling – the ability to listen for an event once (like jQuery’s once). You can write your own code to simply ignore later events, but the event handling code is still there.  It would be better to unbind, but with Backbone that means holding on to the callback function so you can unbind it on the first callback, and to do that you have to assign your callback to a variable which can clutter up simple event handling code.

Or you can just write a bindOnce function that does that for you which is what I did. I feel like this should be a standard feature, so I’ve packaged it up with some tests and submitted it to the Backbone folks in pull request 663. Usage is simple and looks like this:

obj.bindOnce('event', function(){
   obj.counterA += 1;
});

Update 10/29/11

Wow, that was quick. My bindOnce is now part of Backbone with the updated name of once (which makes sense since it matches jQuery). It always speeds things up when you include the tests :)