19

我一直在尝试使用 _lodash.debounce() 并且可以正常工作。但是我不确定它是否以最好的方式工作。我查看了 lodash 网站上的示例,它们似乎只是不传递参数的简单示例。这是我所拥有的:

$scope.parsePid = _.debounce(function () {
    $scope.$apply(function () {
        var pid = $scope.option.sPidRange;
        if (pid == null || pid === "") {
            $scope.pidLower = null;
            $scope.pidUpper = null;
        }
        else if (pid.indexOf("-") > 0) {
            pid = pid.split("-");
            $scope.pidLower = parseInt(pid[0]);
            $scope.pidUpper = parseInt(pid[1]);
        }
        else {
            $scope.pidLower = parseInt(pid);
            $scope.pidUpper = null;
        }
    });
}, 1500);

上面的代码返回一个$scope.parsePid去抖动的函数。请注意,在第 4 行,我得到了 的值$scope.option.SPidRange并在函数中使用它。我真的很想以某种方式传递这个参数,而不是这样获取它。

我这样调用函数:

$scope.$watch("option.sPidRange", function (pid) {
    if (pid !== null) {
        $scope.parsePid();
    }
});

这里的值 pid 应该等于$scope.parsePid

我想将这个 pid 值传递给 debounced 函数,但我不知道该怎么做。我尝试了一些不同的方法,但 debounce 功能给出了错误。

是否可以将参数传递给 debounced function $scope.parsePid()

4

1 回答 1

12

更新

您应该将参数传递给函数:_.debounce(function (pid) {

去抖动的例子

$scope.parsePid = _.debounce(function(pid){
  $scope.$apply(function(){
    if (pid === null || pid === "") {
      $scope.pidLower = null;
      $scope.pidUpper = null;
    } else if (pid.indexOf("-") > 0) {
      pid = pid.split("-");
      $scope.pidLower = parseInt(pid[0],10);
      $scope.pidUpper = parseInt(pid[1],10);      
    } else {
      $scope.pidLower = parseInt(pid,10);
      $scope.pidUpper = null;
    }      
  });
},1500);

我会使用内置的 $timeout

$timeout 示例

var promise;

$scope.parsePid = function(pid){
  $timeout.cancel(promise);
  promise = $timeout(function(){     
    if (pid === null || pid === "") {
      $scope.pidLower = null;
      $scope.pidUpper = null;
    } else if (pid.indexOf("-") > 0) {
      pid = pid.split("-");
      $scope.pidLower = parseInt(pid[0],10);
      $scope.pidUpper = parseInt(pid[1],10);      
    } else {
      $scope.pidLower = parseInt(pid,10);
      $scope.pidUpper = null;
    }
  },1500);
};
于 2014-01-14T10:51:02.103 回答