2015-09-10 33 views
2

当_.debounce被多次调用时,它仅适用于最后一次调用的参数。lodash.debounce获取上一个函数的调用参数

var f = _.debounce(function(a) { 
    console.log(a); 
}) 

f(12) 
f(1223) 
f(5) 
f(42) 

//output -----> 42 

有没有办法让前一个函数的调用参数呢?

例如:

var f = _.customDebounce(function(a) { 
    console.log(a); 
}) 

f(12) 
f(1223) 
f(5) 
f(42) 

//output -----> [12, 1223, 5, 42] 

回答

0

下面是跟踪其参数的简单去抖。它并不试图模仿_.debounce

function customDebounce(func, wait) { 
 
    var args = []; 
 
    var timeoutId; 
 
    return function() { 
 
    // User formal parameters to make sure we add a slot even if a param 
 
    // is not passed in 
 
    if (func.length) { 
 
     for (var i = 0; i < func.length; i++) { 
 
     if (!args[i]) { 
 
      args[i] = []; 
 
     } 
 
     args[i].push(arguments[i]); 
 
     } 
 
    } 
 
    // No formal parameters, just track the whole argument list 
 
    else { 
 
     args.push(_.toArray(arguments)); 
 
    } 
 
    clearTimeout(timeoutId); 
 
    timeoutId = setTimeout(function() { 
 
     func.apply(this, args); 
 
     args = []; 
 
    }, wait); 
 
    } 
 
} 
 

 
// For named arguments, each of the arguments becomes an array that tells 
 
// you how many times it was called 
 
var f = customDebounce(function(a, b, c) { 
 
    console.log('Debounced func called', 
 
    a.length, 
 
    'times', JSON.stringify({ 
 
     a: a, 
 
     b: b, 
 
     c: c 
 
    })); 
 
}); 
 

 
f(1, 3); 
 
f(2, 3, 5); 
 
f(3); 
 
f(4, 2, 3); 
 
// Debounced func called 4 times 
 
// {"a":[1,2,3,4],"b":[3,3,null,2],"c":[null,5,null,3]} 
 

 

 

 
// Can also be used with unnamed arguments, parameters are passed a little 
 
// differently, each element in `arguments` is the array of arguments for 
 
// that call, the latest one being at the end of the array 
 
var g = customDebounce(function() { 
 
    console.log('Debounced no params func called ', 
 
    arguments.length, 
 
    'times', 
 
    JSON.stringify({ 
 
     args: _.toArray(arguments) 
 
    })); 
 
}); 
 

 
g(1, 3); 
 
g(2, 3, 5); 
 
g(3); 
 
g(4, 2, 3); 
 

 
// Debounced no params func called 4 times 
 
// {"args":[[1,3],[2,3,5],[3],[4,2,3]]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

0

最后一个参数我finaly做我自己的实现这个功能,延长lodash:

_.mixin({ 
    debounceArgs: function(fn, options) { 
     var __dbArgs = [] 
     var __dbFn = _.debounce(function() { 
      fn.call(undefined, __dbArgs); 
      __dbArgs = [] 
     }, options); 
     return function() { 
      __dbArgs.push(_.values(arguments)); 
      __dbFn(); 
     } 
    }, 
    throttleArgs: function(fn, options) { 
     var _thArgs = [] 
     var _thFn = _.throttle(function() { 
      fn.call(undefined, _thArgs); 
      _thArgs = [] 
     }, options); 
     return function() { 
      _thArgs.push(_.values(arguments)); 
      _thFn(); 
     } 
    }, 
}) 

用法:

_.debounceArgs(function(a) { 
    console.log(a); 
}) 
相关问题