debounce获取前一个函数的调用参数
lodash.debounce get previous function's call arguments
当_d .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]
我最终自己实现了这个函数,扩展了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);
})
下面是跟踪其参数的简单解析。它不会模仿_.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>
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 我可以在json对象中添加一个函数吗
- Javascript使函数一个接一个地执行
- 是JavaScript中的函数一个对象
- 两个几乎相等的jQuery函数;一个适用于IE,一个不适用于IE
- 两个Javascript函数一个window.onload=Custom.init;和一个window.onload=f
- 使javascript加载函数一个接一个地执行
- 如何通过两个嵌套的匿名函数(一个带有超时的事件处理程序)传递变量
- 为什么我不能让两个jQuery函数一个在另一个里面呢?
- 给函数一个变量名,而不是它的值
- 如何使用嵌入函数(一个滚动页由Pete - peachananr)
- 是否有可能给JavaScript函数一个类型/类?
- 确保两个函数一个接一个地执行,其中第一个函数内部有一个异步调用
- 两个不同的ajax函数一个接一个调用返回相同的值
- jQuery第一次更改函数一个工作
- 给这个函数一个id
- 如何给回调函数一个值一个变量在特定时刻
- 使用回调使两个函数一个接一个地运行
- 两个函数(一个用php)是否可以用“;onclick”;
- 两个几乎相同的函数.一个函数用Queue进行排队.Jquery效果在queued函数上不起作用.为什么