Pete BD 为 debounce 服务提供了一个良好的开端,但是,我发现了两个问题:
- 如果您需要在调用者中更改状态,则应在发送使用 javascript 闭包的 work() 回调时返回。
- 超时变量 - 超时变量不是问题吗?超时[] 也许?想象一下使用 debounce 的 2 个指令 - 信号器、输入表单验证器、
我相信工厂方法会崩溃。
我目前使用的是什么:
我将工厂更改为服务,因此每个指令都会获得一个新的去抖动实例,也就是超时变量的新实例。 - 我还没有遇到过 1 个指令需要超时才能超时的情况。
.service('reactService', ['$timeout', '$q', function ($timeout, $q) {
this.Debounce = function () {
var timeout;
this.Invoke = function (func, wait, immediate) {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
if (timeout) {
$timeout.cancel(timeout);
}
timeout = $timeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
return this;
}
}]);
在我的 angularjs 远程验证器中
.directive('remoteValidator', ['$http', 'reactService', function ($http, reactService) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var newDebounce = new reactService.Debounce();
var work = function(){
//....
};
elm.on('blur keyup change', function () {
newDebounce.Invoke(function(){ scope.$apply(work); }, 1000, false);
});
}
};
}])