How to write a debounce service in AngularJS

前端 未结 7 707
说谎
说谎 2020-11-27 11:01

The underscore library provides a debounce function that prevents multiple calls to a function within a set period of time. Their version makes use of setTimeout.

H

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 11:51

    https://github.com/capaj/ng-tools/blob/master/src/debounce.js

    usage:

    app.directive('autosavable', function(debounce) {
        return {
            restrict : 'A',
            require : '?ngModel',
            link : function(scope, element, attrs, ngModel) {
                var debounced = debounce(function() {
                    scope.$broadcast('autoSave');
                }, 5000, false);
    
                element.bind('keypress', function(e) {
                    debounced();
                });
            }
        };
    });
    

提交回复
热议问题