简体   繁体   English

在回调中访问 arguments (javascript)

[英]Accessing arguments within a callback (javascript)

I'm trying to write a "debounce" function, and I'm stuck in one segment of the code.我正在尝试编写“去抖动”function,但我被困在代码的一部分中。 In the code below, I pass a callback into addEventListener and I wrap it in a debounce function.在下面的代码中,我将回调传递给addEventListener并将其包装在debounce function 中。

This function will have more functionality later, but for now, I just want it to return a function, that will set a timeout for delay milliseconds and then call the original function with the argument (in this case e ).这个 function 稍后将具有更多功能,但现在,我只希望它返回一个 function,它将设置delay毫秒的超时,然后使用参数调用原始e

My problem is on the line in the debounce function that says callback("original-args") .我的问题出在debounce function 中,上面写着callback("original-args") I would like to replace "original-args" with the actual argument that was passed into the callback.我想用传递给回调的实际参数替换“original-args”。 How do I get access to that argument?我如何获得该论点?

  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)
    }
  }

You can do something like the following:您可以执行以下操作:

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

So you can pass the ...args down to your debounced function.因此,您可以将...args传递给您的去抖动 function。 The ...args is a spread operator that means take any number of arguments and store them inside the variable args . ...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