Skip to content

Instantly share code, notes, and snippets.

@fgrehm
Created November 21, 2012 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgrehm/4127812 to your computer and use it in GitHub Desktop.
Save fgrehm/4127812 to your computer and use it in GitHub Desktop.
Backbone.Events.once
// Based on
// https://github.com/tbranyen/backbone/blob/70eed5bc9e5d3587bd85e9ff56f8ea99a7f8501d/backbone.js#L130-141
// Bind an event like `on`, but unbind the event following the first trigger.
window.Backbone.Model.prototype.once =
window.Backbone.View.prototype.once =
window.Backbone.Events.once = function (events, callback, context) {
  // Bind the original events.
  this.on(events, callback, context);
  // Bind a new event immediately preceeding the original to unbind the original once called.
  this.on(events, function unbind() {
    // Remove the original event and the cleanup event.
    this.off(events, callback, context).off(events, unbind);
  }, this);
  return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment