我可以将参数传递给使用_.lodash去抖动的函数吗?

时间:2014-01-14 10:03:55

标签: javascript angularjs lodash

我一直在尝试使用_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函数,但我不确定 这该怎么做。我尝试了一些不同的东西,但去抖功能给出了一个 错误。

是否可以将参数传递到去抖动的function $scope.parsePid()

1 个答案:

答案 0 :(得分:10)

更新

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

An example with debounce

$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

An example with $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);
};
相关问题