如何编写AngularJS去抖服务 [英] How to write a debounce service in AngularJS

查看:116
本文介绍了如何编写AngularJS去抖服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下划线库提供了一个反跳函数prevents多次调用函数设定的时间段之内。他们的版本采用的setTimeout的。

The underscore library provides a debounce function that prevents multiple calls to a function within a set period of time. Their version makes use of setTimeout.

我们怎么能做到这一点在纯AngularJS code?

How could we do this in pure AngularJS code?

此外,我们可以利用$ Q风格的承诺期去抖后检索从被调用函数的返回值?

Moreover, can we make use of $q style promises to retrieve the return value from the called function after the debounce period?

推荐答案

下面是这种服务的工作示例:的 http://plnkr.co/edit/fJwRER?p=$p$pview
它创建时去抖功能终于打来电话,将解决的 $ Q 延期对象。

Here is a working example of such a service: http://plnkr.co/edit/fJwRER?p=preview. It creates a $q deferred object that will be resolved when the debounced function is finally called.

每次防抖动函数被调用的承诺到内部功能的下次调用返回。

Each time the debounce function is called the promise to the next call of the inner function is returned.

// Create an AngularJS service called debounce
app.factory('debounce', ['$timeout','$q', function($timeout, $q) {
  // The service is actually this function, which we call with the func
  // that should be debounced and how long to wait in between calls
  return function debounce(func, wait, immediate) {
    var timeout;
    // Create a deferred object that will be resolved when we need to
    // actually call the func
    var deferred = $q.defer();
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if(!immediate) {
          deferred.resolve(func.apply(context, args));
          deferred = $q.defer();
        }
      };
      var callNow = immediate && !timeout;
      if ( timeout ) {
        $timeout.cancel(timeout);
      }
      timeout = $timeout(later, wait);
      if (callNow) {
        deferred.resolve(func.apply(context,args));
        deferred = $q.defer();
      }
      return deferred.promise;
    };
  };
}]);

您使用则方法上的承诺得到了去抖函数的返回值。

You get the return value from the debounced function by using the then method on the promise.

$scope.logReturn = function(msg) {
  var returned = debounce($scope.addMsg, 2000, false);
  console.log('Log: ', returned);
  returned.then(function(value) {
    console.log('Resolved:', value);
  });
};

如果你调用 logReturn 快速连续多次你会看到承诺登录一遍又一遍,但只有一个解决的消息。

If you call logReturn multiple times in quick succession you will see the promise logged over and over but only one resolved message.

这篇关于如何编写AngularJS去抖服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆