0

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.

2
  • You can't rebind this in an arrow function. see: can-you-bind-this-in-an-arrow-function Commented Jan 25, 2021 at 15:36
  • I know. So how do I include this line event.stopPropagation() in the handler function, so that can keep using this line myButton.addEventListener("click", clickHandler.bind(null, var1, var2))? Basically I am trying to avoid using the arrow function as the handler. Commented Jan 25, 2021 at 15:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.