Skip to content

Instantly share code, notes, and snippets.

@gr2m
Created November 25, 2011 15:07
Show Gist options
  • Save gr2m/1393733 to your computer and use it in GitHub Desktop.
Save gr2m/1393733 to your computer and use it in GitHub Desktop.
Extend `Backbone.Events` with a `debounce` method.
# works exactly like `.bind()`, with the difference that it gets executed with a delay.
# Each time the event gets triggered again, the delay gets reset.
#
# based on: http://benalman.com/projects/jquery-throttle-debounce-plugin/
#
# example:
#
# car = new Backbone.Model
# bind_triggered = debounce_triggered = 0
#
# car.bind 'change', -> bind_triggered++
# car.debounce 'change', 100, -> debounce_triggered++
#
# car.set(ctr: i) for i in [1..3]
# => bind_triggered is 3
# => debounce_triggered is 0. After 0.1 seconds, it will be 1
#
Backbone.Events.debounce = (event, delay, callback) ->
timeout = 0
debounced = ->
window.clearTimeout(timeout)
timeout = window.setTimeout ( ->
callback()
timeout = 0
), delay
@bind event, debounced
Backbone.Model.prototype.debounce = Backbone.Events.debounce
Backbone.Collection.prototype.debounce = Backbone.Events.debounce
Backbone.Router.prototype.debounce = Backbone.Events.debounce
Backbone.View.prototype.debounce = Backbone.Events.debounce
Backbone.Events.debounce = function(event, delay, callback) {
var debounced, timeout;
timeout = 0;
debounced = function() {
window.clearTimeout(timeout);
return timeout = window.setTimeout((function() {
callback();
return timeout = 0;
}), delay);
};
return this.bind(event, debounced);
};
Backbone.Model.prototype.debounce = Backbone.Events.debounce;
Backbone.Collection.prototype.debounce = Backbone.Events.debounce;
Backbone.Router.prototype.debounce = Backbone.Events.debounce;
Backbone.View.prototype.debounce = Backbone.Events.debounce;
@buzzedword
Copy link

Why not use the _.debounce method underscore offers?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment