add debounce service, with mock tests

This commit is contained in:
Joe Fleming 2014-10-27 11:33:47 -07:00
parent 6564f40054
commit 657a49e7dd
3 changed files with 57 additions and 0 deletions

View file

@ -0,0 +1,49 @@
// Debounce service, angularized version of lodash debounce
// borrowed heavily from https://github.com/shahata/angular-debounce
define(function (require) {
var _ = require('lodash');
var module = require('modules').get('kibana');
module.service('debounce', ['$timeout', function ($timeout) {
return function (func, wait, options) {
var timeout, args, context, result;
options = _.defaults(options, {
leading: false,
trailing: true
});
function debounce() {
context = this;
args = arguments;
var later = function () {
timeout = null;
if (!options.leading || options.trailing) {
result = func.apply(context, args);
}
};
var callNow = options.leading && !timeout;
if (timeout) {
$timeout.cancel(timeout);
}
timeout = $timeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
}
debounce.cancel = function () {
$timeout.cancel(timeout);
timeout = null;
};
return debounce;
};
}]);
});

View file

@ -98,6 +98,7 @@
'specs/filters/rison',
'specs/filters/short_dots',
'specs/filters/start_from',
'specs/services/debounce',
'specs/services/storage',
'specs/services/persisted_log',
'specs/services/url',

View file

@ -0,0 +1,7 @@
define(function (require) {
describe('debounce service', function () {
it('should delay execution');
it('should fire on leading edge');
it('should only fire on leading edge');
});
});