繁体   English   中英

Javascript:如何调整反跳功能以采用IF条件?

[英]Javascript: How do I tweak my debounce function to take an IF conditional?

我发现了一个错误,并对其进行了跟踪。
您可以在这里看到我的代码的简化示例

事实证明,我需要对if()语句进行反跳操作,而不是对函数本身进行反跳操作。
我想将反跳功能保留为独立功能,但不确定如何传递条件输入。

有什么指针吗?

这是代码:

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!!');
}

以您的示例为例,为什么不以arg 1的形式传递切换...类似于:

var toggle = true;
var debouncedFunk = function(toggle) {
  if (toggle)
    // the function call
  else
    // something else
};
debounce(debouncedFunk, toggle, 1250);

你也应该考虑使用函数对象.call.apply的方法。 它们用于调用函数并传递参数。 以示例函数为例:

var example = function(one, two) { 
  // Logic here
};

您可以通过三种方式调用它:

// First
example(1, 2);
// Second
example.call({}, 1, 2);
// Third
example.apply({}, [ 1, 2 ]);

第一种是调用函数的标准方法。 在第一和之间的差.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);
};

将您的电流更改为:

var toggle = true;
var debouncedFunk = function(toggle) {
  if (toggle)
    // Do if true
  else
    // DO if false
};
debounce(debouncedFunk, 1000, toggle);

也许信息太多(对不起)?

最后一点,我建议使用一个框架(如果可能),其中已经实现了这些功能(以及许多其他有用的功能),例如Underscore 使用Underscore,您的示例如下所示:

// Define debouncedFunk and toggle
debouncedFunk = _.bind(debouncedFunk, {}, toggle);
debouncedFunk = _.debounce(debouncedFunk, 1000);
debouncedFunk();

编辑

修复了下划线示例, _.debounce返回仅在延迟之后执行的函数,但仍需要调用该函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM