Skip to content

Instantly share code, notes, and snippets.

@kaineer
Last active August 29, 2015 14:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kaineer/c26b813b866e7464270e to your computer and use it in GitHub Desktop.
Debouncing backbone view
// 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);
<!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