如何在AngularJS中编写反跳服务

如何在AngularJS中编写反跳服务,第1张

如何在AngularJS中编写反跳服务

这是此类服务的工作示例:http :
//plnkr.co/edit/fJwRER?p=preview。它创建了一个

$q
延迟对象,该对象将在最终调用抖动功能时解决。

每次

debounce
调用该函数时,都会返回对内部函数的下一次调用的承诺。

// Create an AngularJS service called debounceapp.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;    };  };}]);

通过在promise上使用then方法,可以从去抖动的函数中获取返回值。

$scope.addMsg = function(msg) {    console.log('addMsg called with', msg);    return msg;};$scope.addMsgDebounced = debounce($scope.addMsg, 2000, false);$scope.logReturn = function(msg) {    console.log('logReturn called with', msg);    var promise = $scope.addMsgDebounced(msg);    promise.then(function(msg) {        console.log('Promise resolved with', msg);    });};

如果您

logReturn
连续快速拨打了多次电话,您将看到
logReturn
一遍又一遍的通话记录,但只有一个
addMsg
通话记录。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642034.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存