簡體   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