栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在AngularJS中编写反跳服务

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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
通话记录。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636174.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号