Created
November 25, 2011 15:07
-
-
Save gr2m/1393733 to your computer and use it in GitHub Desktop.
Extend `Backbone.Events` with a `debounce` method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not use the _.debounce method underscore offers?