简体   繁体   English

使用 bind() 将多个 arguments 和事件传递给事件处理程序

[英]Passing multiple arguments and event to event handler using bind()

I want to use the .bind solution to implement event handler as per some latest solution in this thread here .我想使用.bind解决方案按照这里线程中的一些最新解决方案实现事件处理程序。

However, suppose my original handler is as following:但是,假设我的原始处理程序如下:

const clickHandler = (arg1, arg2) => {
   ...do stuff...
}

let var1 = "text1"
let var2 = "text2"
myButton.addEventListener("click", clickHandler.bind(null, var1, var2))

If I need to add a line like this, which requires the event argument, to the handler:如果我需要向处理程序添加这样的需要event参数的行:

const clickHandler = (arg1, arg2) => {
   event.stopPropagation()
   ...do stuff...
}

If I do without using .bind , this would work:如果我不使用.bind ,这将起作用:

const clickHandler = (arg1, arg2) => {
   ...do stuff...
}

let var1 = "text1"
let var2 = "text2"
myButton.addEventListener("click", (event) => {
   event.stopPropagation()
   clickHandler(var1, var2)
})

But if I want to make it concise using .bind , how should I pass event into the handler?但是,如果我想使用.bind使其简洁,我应该如何将event传递给处理程序? Thanks.谢谢。

Any arguments passed to bind() after the first are prepended to the arguments provided to the function when it is created, in this case event .在第一个之后传递给bind()的任何 arguments 在创建时添加到提供给 function 的 arguments 之前,在本例中为event This means that in the resulting bound callback the event will be the last argument the callback receives, rather than the first as is normal if not using bind.这意味着在生成的绑定回调中, event将是回调接收的最后一个参数,而不是第一个参数,如果不使用绑定则正常。 this remains unchanged as it is an arrow function. this保持不变,因为它是一个箭头 function。

If you are passing a consistent, known number of arguments in each bind() you can access them directly.如果您在每个bind()中传递一致的已知数量的 arguments,您可以直接访问它们。

const clickHandler = (arg1, arg2, event) => {
...
}

Otherwise, if the number of bound arguments will vary you can access the event by retrieving the last element from the arguments iterator.否则,如果绑定的 arguments 的数量会发生变化,您可以通过从arguments迭代器中检索最后一个元素来访问该event

const clickHandler = (...args) => {
  const event = args.pop();
...
}

 const myButton = document.getElementById('button'); const clickHandler = (...args) => { const event = args.pop(); console.log(event.target); console.log('args: ', args); } let var1 = "text1" let var2 = "text2" myButton.addEventListener("click", clickHandler.bind(null, var1, var2));
 <button type='button' id='button'>Button</button>

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

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