Ramen was recently working on a Vue based component that needed to bind mouse events via addEventListener, but ran into a problem. You need to pass parameters when you bind an anonymous function, which is easy, of course, but tricky when you want to remove the anonymous function dynamically. Is there a way I can pass parameters without using an anonymous function so I can easily remove it later using removeEventListener? B: of course!

The problem

There is the following code:

// bind event
element.addEventListener('click', _bindEventHandler)
// unbind event
element.removeEventListener('click', _bindEventHandler)
Copy the code

What if I’m passing parameters using a named function? Of course you can:

element.addEventListener('click'.function() {
  _bindEventHandler(param1, param2)
})
Copy the code

Problem analysis and solution

However, the problem with this is that if I want to remove the binding event synchronously, I cannot remove it because there is no function name and we cannot remove it directly with removeEventListener. So, there is a curve saving method, that is to bind the parameters directly to the element, because when we use named functions, the addEventListener silently passes the event of the event to the function. So when we want to retrieve these parameters, we can retrieve them directly through event.target.

// Set parameters
element._params = { param1, param2 }
// Bind events
element.addEventListener('click', _bindEventHandler)
// Get arguments in the function
function _bindEventHandler(event) {
  const params = event.target._params
  / /... do sth after
}
Copy the code

OK, so we can realize the parameter passing, and also very easy to remove the binding event! Are you happy?

one more thing

One problem is that my bound Element event needs extra processing when it encounters an event delegate. For example, when we bind a hierarchical button or DOM, when we click on the internal DOM, we will not get the parameters set on the DOM of the actual binding event. Here we need to get the parameters by iterating through the object bound to the event.

We can retrieve parameters from the Dom via event.path(event.composedPath())