Written in the book of the former

What you missed: The second argument to addEventListener can be passed not only to a function, but also to an object that implements the EventListener interface.

Description in the document

listener

An Event notification (object that implements the Event interface) object is received when the Event type being listened on fires. The listener must be either an object that implements the EventListener interface, or a function

From MDN

I always pass a function in the listener to implement some logic by listening for events to happen. However, when you first see “an object implementing the EventListener interface” in the documentation, you learn that this object refers to an object containing the handleEvent method.

var obj = {
   // ...
    handleEvent: function(event) {
        // ...
        console.log('event', event)
    }
}
document.body.addEventListener('click', obj, false)
Copy the code

The method is called when an event registered by EventListener occurs, and an event parameter is passed into the method.

So once you know the concept what are the benefits of this knowledge for actual development

Application under development

An 🌰

var obj = {
    a: 1.handleEvent: function(event) {
        alert(this.a)
    }
}
document.body.addEventListener('click', obj, false) / / 1
document.body.addEventListener('click', obj.handleEvent, false) // undefined
Copy the code

As you can see from the example, the binding obj affects the orientation of this. That is, we can take advantage of this feature to use private properties or methods in OBJ when handling events

Raise an 🌰 again

var obj = {
    a: 1.handleEvent: function(event) {
        alert(this.a)
    }
}
var anotherHandler = function(event) {
    alert('hello world')}document.body.addEventListener('click', obj, false) / / 1
setTimeout(function(){
    obj.handleEvent = anotherHandler // hello world
},2000)

Copy the code

As you can see from this example, this form of event binding is a convenient way to dynamically change the logic used to handle events. You don’t need to remove and then add.

Write in the last

The downside of this binding approach is not compatibility, but readability. I was very confused when I saw this when I read other people’s source code (my personal level is also a certain reason), and I didn’t know there was such a binding event writing method until I looked up the information.

Therefore, when using this method in daily work development, it is best to make sure that the development partner is also aware of this method to avoid conflicts in collaboration.

reference

MDN EventListener

MDN EventTarget.addEventListener()

HandleEvent and addEventListener

practice

This post appears in Roy’s Blog