Remove event listener in javascript

You’ve Got Options for Removing Event Listeners

Reviewing some of the most common approaches available to remove event listeners in JavaScript.

Cleaning up your code in runtime is a non-negotiable part of building efficient, predictable applications. One of the ways that’s done in JavaScript is by stewarding event listeners well — specifically, removing them when they’re no longer needed.

There are several approaches available to do this, each with its own set of trade-offs that make it more appropriate in certain circumstances. We’re gonna run through a few of the most often used tactics, as well as a few considerations to keep in mind when you’re trying to decide which is best for the job at any given time.

We’ll be tinkering with the following setup — a button with a single click event listener attached:

button id="button">Do Somethingbutton> script> document.getElementById('button').addEventListener('click', () =>  console.log('clicked!'); >); script> 

Using Chrome’s getEventListeners() function, you’d see just one listener attached to that element:

In the event that you’d need to remove that listener, here’s what you might reach for.

Using .removeEventListener()

It’s probably the most obvious, but also the one with the most potential to threaten your sanity. The .removeEventListener() method accepts three parameters: the type of listener to remove, the callback function for that listener, and an options object.

But herein lies the (potentially) tricky part: those exact parameters must exactly match what were used when then the listener was set up, including the same reference in to the callback in memory. Otherwise, .removeEventListener() does nothing.

With that in mind, this would be totally ineffective:

document.getElementById('button').addEventListener('click', () =>  console.log('clicked!'); >); document.getElementById('button').removeEventListener('click', () =>  console.log('clicked!'); >); 

Even though that callback looks identical to the one originally attached, it’s not the same reference. The solution to this is to set the callback to a variable and reference it in both .addEventListener() and .removeEventListener() .

const myCallback = () =>  console.log('clicked!'); >; document.getElementById('button').addEventListener('click', myCallback); document.getElementById('button').removeEventListener('click', myCallback); 

Or, for particular use cases, you could also remove the listener by referencing a pseudo-anonymous function from within the function itself:

document .getElementById('button') .addEventListener('click', function myCallback()  console.log('clicked!'); this.removeEventListener('click', myCallback); >); 

Despite its particularity, .removeEventListener() has the advantages of being very explicit in its purpose. There’s zero doubt as to what it’s doing when you’re reading through the code.

Using .addEventListener() ’s once Option

The .addEventListener() method comes with a tool to help clean itself up if it’s intended for a one-time use: the once option. It’s about as simple as it sounds. If it’s set to true , the listener will automatically remove itself after first being invoked:

const button = document.getElementById('button'); button.addEventListener('click', () =>  console.log('clicked!'); >,  once: true >); // 'clicked!' button.click(); // No more listeners! getEventListeners(button) // <> 

Assuming it fits your use case, this approach might be appropriate if you’re keen on using an anonymous function, given that your listener only needs to be invoked once.

Cloning & Replacing the Node

Sometimes, you don’t know about all the listeners active on a given node, but you do know you want to nuke them. In that case, it’s possible to clone the entire node and replace itself with that clone. Using the .cloneNode() method, none of the listeners attached via .addEventListener() will be carried over, giving it a clean slate.

Back in the stone age of client-side JavaScript, you would’ve seen this done by querying up to the parent, and replacing a particular child node with a clone:

.parentNode.replaceChild(button.cloneNode(true), button); 

But in modern browsers, that can be simplified with .replaceWith() :

.replaceWith(button.cloneNode(true)); 

The one thing that could potentially trip you up here is that intrinsic listeners are preserved, meaning a button with an onclick attribute would still fire as defined:

button id="button" onclick="console.log('clicked!')"> Do Something button> 

In all, it’s an option worth reaching for if you need to indiscriminately remove listeners of any sort with brute force. On the downside, however, it suffers from being less obvious about its purpose. Some might go so far as to call it a hack.

Using AbortController()

This one’s new to me. I literally just read about it when I came across this tweet from Caleb Porzio. If you’re like me, you might’ve only heard of an AbortController being used to cancel fetch() requests. But it’s apparently more flexible than that.

As of recently, .addEventListener() can be configured with a signal for imperatively aborting/removing a listener. When the respective controller calls .abort() , that signal will trigger the listener to be removed:

const button = document.getElementById('button'); const controller = new AbortController(); const  signal > = controller; button.addEventListener('click', () => console.log('clicked!'),  signal >); // Remove the listener! controller.abort(); 

The most apparent advantage to this might be the ergonomics. It’s (in my opinion) a much clearer way of removing a listener without the potential gotcha of dealing with .removeEventListener() . But there’s a more tactical advantage too: you can use one signal to remove multiple listeners, of any sort, all at once. And using anonymous functions is totally fine too:

const button = document.getElementById('button'); const controller = new AbortController(); const  signal > = controller; button.addEventListener('click', () => console.log('clicked!'),  signal >); window.addEventListener('resize', () => console.log('resized!'),  signal >); document.addEventListener('keyup', () => console.log('pressed!'),  signal >); // Remove all listeners at once: controller.abort(); 

The only cause for hesitancy I came across is browser support. It’s a relatively new feature, with full support existing in Chrome only since 2021 (v90). So, keep this in mind if you need to support browser versions beyond only a couple years old.

Which Should I Choose?

As with everything else, “it depends.” Still, here’s how I might choose one over the other at a moment’s notice:

  • Use .removeEventListener() if the callback function is assigned to a variable and within easy reach of where the listener was added.
  • Use the once option in .addEventListener() if you need to fire a callback only once (duh).
  • Use the clone & replace approach if you need to indiscriminately nuke multiple listeners in one fell swoop.
  • Use AbortController() if you have a series of listeners you’d like to imperatively remove at once, or if you just like the syntax.

What’s Missing?

It’s very possible I’m missing another option in addition to these. If you happen to have one, feel free to drop a comment or let me know by some other means. At the very least, I hope this helps to mentally organize some of the the several paths available to clean up event listeners, and to also help prep your brain for the next time you need to manage them in your code.

Источник

EventTarget: removeEventListener() method

The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.

Calling removeEventListener() with arguments that do not identify any currently registered event listener on the EventTarget has no effect.

If an event listener is removed from an EventTarget while another listener of the target is processing an event, it will not be triggered by the event. However, it can be reattached.

Warning: If a listener is registered twice, one with the capture flag set and one without, you must remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

Syntax

removeEventListener(type, listener) removeEventListener(type, listener, options) removeEventListener(type, listener, useCapture) 

Parameters

A string which specifies the type of event for which to remove an event listener.

The event listener function of the event handler to remove from the event target.

An options object that specifies characteristics about the event listener.

The available options are:

  • capture : A boolean value that specifies whether the event listener to be removed is registered as a capturing listener or not. If this parameter is absent, the default value false is assumed.

A boolean value that specifies whether the event listener to be removed is registered as a capturing listener or not. If this parameter is absent, the default value false is assumed.

Return value

Matching event listeners for removal

Given an event listener previously added by calling addEventListener() , you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener() . But what about the options or useCapture parameters?

While addEventListener() will let you add the same listener more than once for the same type if the options are different, the only option removeEventListener() checks is the capture / useCapture flag. Its value must match for removeEventListener() to match, but the other values don’t.

For example, consider this call to addEventListener() :

.addEventListener("mousedown", handleMouseDown, true); 

Now consider each of these two calls to removeEventListener() :

.removeEventListener("mousedown", handleMouseDown, false); // Fails element.removeEventListener("mousedown", handleMouseDown, true); // Succeeds 

The first call fails because the value of useCapture doesn’t match. The second succeeds, since useCapture matches up.

.addEventListener("mousedown", handleMouseDown,  passive: true >); 

Here, we specify an options object in which passive is set to true , while the other options are left to the default value of false .

Now look at each of these calls to removeEventListener() in turn. Any of them in which capture or useCapture is true fail; all others succeed.

Only the capture setting matters to removeEventListener() .

.removeEventListener("mousedown", handleMouseDown,  passive: true >); // Succeeds element.removeEventListener("mousedown", handleMouseDown,  capture: false >); // Succeeds element.removeEventListener("mousedown", handleMouseDown,  capture: true >); // Fails element.removeEventListener("mousedown", handleMouseDown,  passive: false >); // Succeeds element.removeEventListener("mousedown", handleMouseDown, false); // Succeeds element.removeEventListener("mousedown", handleMouseDown, true); // Fails 

It’s worth noting that some browser releases have been inconsistent on this, and unless you have specific reasons otherwise, it’s probably wise to use the same values used for the call to addEventListener() when calling removeEventListener() .

Example

This example shows how to add a mouseover -based event listener that removes a click -based event listener.

const body = document.querySelector("body"); const clickTarget = document.getElementById("click-target"); const mouseOverTarget = document.getElementById("mouse-over-target"); let toggle = false; function makeBackgroundYellow()  body.style.backgroundColor = toggle ? "white" : "yellow"; toggle = !toggle; > clickTarget.addEventListener("click", makeBackgroundYellow, false); mouseOverTarget.addEventListener("mouseover", () =>  clickTarget.removeEventListener("click", makeBackgroundYellow, false); >); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

Читайте также:  Что такое tkinter python
Оцените статью