On one hand, if I call method registerClick_1, then tapping my element will give me access to the event argument passed to the function, but inside the callback function, I lose the this object.
On the other hand, if I call method registerClick_2, then I can continue using the this object (which I like as I have access to its fields and other methods), but I don’t have access to the event argument.
You might use an arrow function for the event handler; there’s no this binding, so you can just refer to the outer this.
That’s actually not true – it still gets passed in any arguments as usual (although you could bind additional arguments as well, which would then be prepended to the other arguments).
So you could use one of these options:
myElement.addEventListener('click', event => {
// Do something
})
myElement.addEventListener('click', function (event) {
// Do something
}.bind(this))
I would like to continue using HammerJS as the mobile gesture framework.
This means that I probably cannot use:
myElement.addEventListener(‘click’, function (event) {
// Do something
}.bind(this))
Can anyone show me an example of how I can still use bind and access the event parameter?
In my example above, how can I access the event parameter inside the objTapped method?
By actually specifying event as a parameter of objTapped()…
objTapped (event) {
console.log(event, this)
}
Again, .bind() doesn’t void any arguments passed in anyway. From the MDN:
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.