簡體   English   中英

在回調中訪問 arguments (javascript)

[英]Accessing arguments within a callback (javascript)

我正在嘗試編寫“去抖動”function,但我被困在代碼的一部分中。 在下面的代碼中,我將回調傳遞給addEventListener並將其包裝在debounce function 中。

這個 function 稍后將具有更多功能,但現在,我只希望它返回一個 function,它將設置delay毫秒的超時,然后使用參數調用原始e

我的問題出在debounce function 中,上面寫着callback("original-args") 我想用傳遞給回調的實際參數替換“original-args”。 我如何獲得該論點?

  button.addEventListener("click", debounce(e => {
    let elem = document.createElement("P"); 
    elem.textContent = "Clicked";
    container.appendChild(elem);
  }, 2000))

  function debounce(callback, delay) {
    return function() {
      setTimeout(() => {
        callback("original-args")
      }, delay)
    }
  }

您可以執行以下操作:

button.addEventListener(
  "click",
  debounce(
    (e) => {
      let elem = document.createElement("P");
      elem.textContent = "Clicked";
      container.appendChild(elem);
    },
    2000
  )
);

function debounce(callback, delay) {
  return function (...args) {
    setTimeout(() => {
      callback(...args);
    }, delay);
  };
}

因此,您可以將...args傳遞給您的去抖動 function。 ...args是一個擴展運算符,這意味着take any number of arguments and store them inside the variable args中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM