Arnaud Leyder
Arnaud Leyder

Reputation: 7002

Can I access event information with JavaScript bind()?

Just trying to wrap my ahead around on this:

var _myFn = function(param1, param2) {
  event.stopPropagation(); // this is what I want = read or affect click event information
  // do stuff with context, param1 and param2
};
element.addEventListener('click', _myFn.bind(context, param1, param2));

I have not read that the bind() method allows to pass the event information for the click. I know I could rewrite my handler logic but is there a way to do this anyway? If not what would be an elegant way to resolve this?

I need an ES5 solution.

Upvotes: 2

Views: 63

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

The actual method parameters will follow the bind parameters

Arguments to prepend to arguments provided to the bound function when invoking the target function.

var _myFn = function(param1, param2, e) {
  e.stopPropagation();
  alert(e.target.tagName)
}
var param1 = 1,
  param2 = 2;
element.addEventListener('click', _myFn.bind(this, param1, param2));
<div id="element">Click me</div>

Upvotes: 5

Related Questions