【问题标题】:debounce not firing inside $scope.$watch [duplicate]在 $scope.$watch 内没有触发 debounce [重复]
【发布时间】:2015-06-04 17:24:53
【问题描述】:

我试图在我的 UI 中更新模型变量时运行一个函数,但我也试图通过去抖动来限制函数执行的频率,因为请求的函数会触发 AJAX 调用。然而,下面的去抖动功能似乎根本没有触发。

我最初编写了自己的 debounce 服务,并使用下划线 debounce 方法来测试我写的内容是否不正确,但事实证明 Angular 只是不喜欢下面的东西......

不能在 HTML 中使用 Angular 的 ng-model-option debounce 方法。

$scope.$watch('filters.monthlyCost', function () {

    _.debounce(function () {
        console.log('lol');
    }, 1000);

});

没有控制台错误,console.log('lol') 永远不会发生。

注意:$watch 执行。

【问题讨论】:

  • 你的手表在执行吗?
  • @PSL 是的,$watch 正在执行。
  • 如果你想在 debounce 上观看,你应该使用模型选项,否则每次模型改变时它总是会触发,即使有下划线 debounce。 docs.angularjs.org/api/ng/directive/ngModelOptions

标签: javascript angularjs underscore.js


【解决方案1】:

由于debounce返回一个函数((Function): Returns the new debounced function.),需要执行debounce的返回值,

例如:

_.debounce(function () {
        console.log('lol');
    }, 1000)();

你可以这样做:

$scope.$watch('monthlyCost', _.debounce(function() {
        console.log('lol');
    }, 1000));

【讨论】:

    【解决方案2】:

    据我了解 _.debounce 的文档(未测试)

    $scope.$watch('filters.monthlyCost', function () {
    
        var logConsole = _.debounce(function () {
            console.log('lol');
            }, 1000);
        logConsole();
    
    });
    

    使用您的代码,您只是注册了一个 debounce 函数,但它不会执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-06
      • 2023-03-26
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2015-12-11
      相关资源
      最近更新 更多