Tristan Tran
Tristan Tran

Reputation: 1513

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.

Upvotes: 0

Views: 1830

Answers (1)

pilchard
pilchard

Reputation: 12919

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>

Per the MDN documentation for bind:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Upvotes: 2

Related Questions