Debouncing backbone view
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
// js/backbone-debounce.js | |
(function(root) { | |
// | |
var DebounceView = function(view) { | |
// | |
var debouncing = view.debounce; | |
var events = _.clone(view.events); | |
if(!debouncing || !events) { | |
return; | |
} | |
_.each(debouncing, function(timeout, eventKey) { | |
var methodName = events[eventKey]; | |
var method; | |
var debouncedMethodName; | |
var debouncedMethod; | |
if(methodName) { | |
method = view[methodName]; | |
if(method) { | |
debouncedMethod = _.debounce(method.bind(view), timeout, true); | |
debouncedMethodName = "__debounced_" + methodName + "_" + timeout; | |
view[debouncedMethodName] = debouncedMethod; | |
events[eventKey] = debouncedMethodName; | |
} | |
} | |
}); | |
view.events = events; | |
}; | |
// | |
root.DebounceView = DebounceView; | |
})(Backbone); |
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
<!doctype html> | |
<html> | |
<head> | |
<title>Boilerplate</title> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone.js"></script> | |
<script src="./js/backbone-debounce.js"></script> | |
<script> | |
$(function() { | |
// | |
var View = Backbone.View.extend({ | |
initialize: function() { | |
this._count = 0; | |
Backbone.DebounceView(this); | |
}, | |
events: { | |
"click .js-count": "count" | |
}, | |
debounce: { | |
"click .js-count": 500 | |
}, | |
count: function() { | |
this._count += 1; | |
this.$(".message").text(this._count + ""); | |
return false; | |
} | |
}); | |
var view = new View({el: ".container"}); | |
}); | |
</script> | |
<style type="text/css"> | |
.message { | |
font-size: 72px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
<a href="#" class="js-count">Count</a> | |
<div class="message">0</div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment