0

有没有人有任何指针让我以角度去抖动按键事件?我无法让它去抖动。而且我肯定知道,因为我正在使用 $log.debug 打印出按下的键,并且它触发的次数不是去抖动率。

我已经这样设置了:

<div ng-keypress="doSomething"></div>

并在我的控制器中(不是我在此实例中包含 underscore.js 以利用其 debounce 方法):

...
$scope.doSomething = function(event, keyEvent) {
    var keypressed = String.fromCharCode(keyEvent.which).toUpperCase();
    _.debounce(handleKeyPress(keypressed), 500);
}

function handleKeyPress(keypressed) {
    //do something with the keypress
}

提前感谢您的帮助。

4

1 回答 1

1

试试下面的代码:

$scope.doSomething = _.debounce(function(event, keyEvent) {
    $scope.$apply(function() {
    // Do something here
    });
}, 500);

工作小插曲

正如@Enzey 所说,_.debounce()返回一个需要在某处调用才能产生任何效果的“去抖动”函数。您需要调用$apply()才能触发摘要循环。否则,在 debounced 函数中对模型所做的任何更改都不会更新视图。

更新

It turned out that what the OP really wanted was a throttled function. Below is another code snippet using _.throttle():

$scope.doSomething = _.throttle(function($event) {
    if ($scope.$$phase) return; // Prevents 'digest already in progress' errors

    $scope.$apply(function() {
        // Do something here
    });
}, 100);
于 2015-04-21T04:28:37.823 回答