我发现了一个错误,并将其追踪.
您可以在此处查看我的代码的简化示例.
事实证明,我需要辩论我的if()陈述,而不是去除功能本身.
我想将debounce作为独立函数保留,但我不确定如何传递条件.
有什么指针吗?
这是代码:
var foo = function(xyz) {
alert(xyz);
};
function setter(func, arg1, arg2) {
return {
fn: func,
arg1: arg1,
arg2: arg2
};
}
function debounce(someObject) {
var duration = someObject.arg2 || 100;
var timer;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
someObject.fn(someObject.arg1);
timer = 0;
}, duration);
}
var toggle = true;
if (toggle) {
debounce(setter(foo, 'The best things in life are worth waiting for.', 1250));
} else {
foo('Instant gratification is sweet!!');
}
Run Code Online (Sandbox Code Playgroud)
使用您的示例,为什么不在arg 1中传递切换...类似于:
var toggle = true;
var debouncedFunk = function(toggle) {
if (toggle)
// the function call
else
// something else
};
debounce(debouncedFunk, toggle, 1250);
Run Code Online (Sandbox Code Playgroud)
您还应该研究使用Function对象.call和.apply方法.它们用于调用函数并传入参数.以示例函数为例:
var example = function(one, two) {
// Logic here
};
Run Code Online (Sandbox Code Playgroud)
您可以通过三种方式调用它:
// First
example(1, 2);
// Second
example.call({}, 1, 2);
// Third
example.apply({}, [ 1, 2 ]);
Run Code Online (Sandbox Code Playgroud)
第一种是调用函数的标准方法.第.call一个参数和第一个参数.call是函数的上下文对象(this将指向函数内部),其他参数在此之后传递(并且需要一个已知列表.call.的好处.apply是您可以将数组传递给参数的函数,它们将被适当地分配给参数列表,第一个参数仍然是上下文对象.
它会简化你的去抖功能,而不必像现在这样处理结构化对象.
你的辩解的建议:
var debounce = function(funk, delay) {
var args = [];
if (arguments.length > 2)
args = [].slice.call(arguments, 2);
setTimeout(function() { funk.apply({}, args); }, delay);
};
Run Code Online (Sandbox Code Playgroud)
将当前的if更改为:
var toggle = true;
var debouncedFunk = function(toggle) {
if (toggle)
// Do if true
else
// DO if false
};
debounce(debouncedFunk, 1000, toggle);
Run Code Online (Sandbox Code Playgroud)
也许有太多的信息(对不起)?
作为最后一点,我建议使用一个框架(如果可能的话)已经实现了这些函数(以及许多其他有用的函数),例如Underscore.使用下划线你的例子看起来像:
// Define debouncedFunk and toggle
debouncedFunk = _.bind(debouncedFunk, {}, toggle);
debouncedFunk = _.debounce(debouncedFunk, 1000);
debouncedFunk();
Run Code Online (Sandbox Code Playgroud)
编辑
修复了下划线示例,_.debounce返回一个仅在延迟后执行但仍需要调用的函数.
| 归档时间: |
|
| 查看次数: |
1619 次 |
| 最近记录: |