When I call addDomListener
or addDomListenerOnce
:
const domNode = document.getElementById('...');
google.maps.event.addDomListener(domNode, "mouseover", () => { ... })
I keep getting the following console warning:
google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead:
https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener
The feature will continue to work and there is no plan to decommission it.
How do I migrate to addEventListener
without breaking anything?
Both addDomListener
and addDomListenerOnce
were deprecated on Apr 7, 2022 but they
…will continue to work and there is no plan to decommission them.
If you want to get rid of the warnings, proceed as follows:
addDomListener
alternativeAs advised in the official docs, you should migrate to the native DOM's addEventListener
.
So instead of:
const domNode = document.querySelector('...');
google.maps.event.addDomListener(domNode, 'mouseover', (evt => {
// handle mouseover
}));
you'd do:
domNode.addEventListener('mouseover', (evt => {
// handle mouseover
}));
In both cases, the listener's evt
argument keeps implementing the DOM Event
interface -- depending on the event type.
addDomListenerOnce
alternativeSimilar to above but with the addition of the once
option. So instead of:
google.maps.event.addDomListenerOnce(domNode, 'click', (evt) => {
// handle clicks
});
you'd do:
domNode.addEventListener('click',
(evt) => {
// handle clicks only once
},
{ once: true }
);
Note that google's addDomListener[Once]
both return a MapsEventListener
.
That's not the case for the DOM's addEventListener
which returns void
.
So if you were previously storing your listeners — usually to remove/detach them later on — you'll need to keep track of them in some other way… Check out How to remove an event listener in javascript? or let the browser's garbage collector detach the listeners for you.
💡 Tip: addEventListener
also supports the passive
option which can greatly improve performance.