Skip to content

Instantly share code, notes, and snippets.

@richsilv
Last active August 29, 2015 14:10
Show Gist options
  • Save richsilv/c63ba439d071f77a68eb to your computer and use it in GitHub Desktop.
Save richsilv/c63ba439d071f77a68eb to your computer and use it in GitHub Desktop.
Mixin for Underscore.js to allow arguments to be passed with each function call. Designed for use with Meteor, but easy to use without either Meteor or Underscore.
// Underscore mixin to allow arguments to be passed to debounced functions.
// Useful for updating user doc on keyup (or similar) where doc update will invalidate
// many dependent computations, and so you only want to actually update it every so often.
// See below for example.
// Can also be used without Meteor (change Meteor.setTimeout to Timeout), and without
// underscore (just make debounceWithArgs a stand-alone function).
_.mixin({
debounceWithArgs: function(func, timeOutDuration) {
var timeOut,
_this = this,
newFunc = function() {
var args = Array.prototype.slice.call(arguments);
if (timeOut) {
Meteor.clearTimeout(timeOut);
}
timeOut = Meteor.setTimeout(function() {
func.apply(_this, args);
Meteor.clearTimeout(timeOut);
timeOut = null;
}, timeOutDuration);
}
return newFunc;
}
});
// Example of how to use in Meteor to debounce keyup:
var userUpdateDebounce = _.debounceWithArgs(function(set) {
Meteor.users.update({_id: Meteor.userId()}, {
$set: set
});
}, 500);
Template.myTemplate.events({
'keyup #input-field': function(event, template) {
var set = {
'profile.field': template.$(event.currentTarget).val()
};
userUpdateDebounce(set);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment