简体   繁体   中英

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 .

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:

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

If I do without using .bind , this would work:

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? 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 . 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. this remains unchanged as it is an arrow function.

If you are passing a consistent, known number of arguments in each bind() you can access them directly.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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