From 115ebf48c774b6711fcd7a6693275923e66f6e8c Mon Sep 17 00:00:00 2001 From: Wesley Cho Date: Mon, 28 Mar 2016 21:11:17 -0700 Subject: [PATCH] feat(perf): debounce resize callback - The resize event fires often, so debouncing the function execution can improve performance dramatically --- src/uiSelectController.js | 8 ++++---- src/uisDebounceService.js | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 src/uisDebounceService.js diff --git a/src/uiSelectController.js b/src/uiSelectController.js index 274c73266..f1a67fc46 100644 --- a/src/uiSelectController.js +++ b/src/uiSelectController.js @@ -5,8 +5,8 @@ * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested. */ uis.controller('uiSelectCtrl', - ['$scope', '$element', '$timeout', '$filter', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector', '$window', - function($scope, $element, $timeout, $filter, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector, $window) { + ['$scope', '$element', '$timeout', '$filter', '$$uisDebounce', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector', '$window', + function($scope, $element, $timeout, $filter, $$uisDebounce, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector, $window) { var ctrl = this; @@ -635,8 +635,8 @@ uis.controller('uiSelectCtrl', ctrl.searchInput.off('keyup keydown tagged blur paste'); }); - angular.element($window).bind('resize', function() { + angular.element($window).bind('resize', $$uisDebounce(function() { ctrl.sizeSearchInput(); - }); + }), 50); }]); diff --git a/src/uisDebounceService.js b/src/uisDebounceService.js new file mode 100644 index 000000000..f92193a94 --- /dev/null +++ b/src/uisDebounceService.js @@ -0,0 +1,24 @@ +/** + * Debounces functions + * + * Taken from UI Bootstrap $$debounce source code + * See https://github.com/angular-ui/bootstrap/blob/master/src/debounce/debounce.js + * + */ +uis.factory('$$uisDebounce', ['$timeout', function($timeout) { + return function(callback, debounceTime) { + var timeoutPromise; + + return function() { + var self = this; + var args = Array.prototype.slice.call(arguments); + if (timeoutPromise) { + $timeout.cancel(timeoutPromise); + } + + timeoutPromise = $timeout(function() { + callback.apply(self, args); + }, debounceTime); + }; + }; +}]);