如何解决 google 地图中的 addDomListener() 弃用问题

How to address addDomListener() deprecation in google maps

当我调用 addDomListeneraddDomListenerOnce 时:

const domNode = document.getElementById('...');
google.maps.event.addDomListener(domNode, "mouseover", () => { ... })

我不断收到以下控制台警告:

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.

如何在不破坏任何东西的情况下迁移到 addEventListener

addDomListeneraddDomListenerOnce 都是 deprecated on Apr 7, 2022 但他们

…will continue to work and there is no plan to decommission them.

如果您想摆脱警告,请按以下步骤操作:

addDomListener备选方案

按照官方文档中的建议,您应该迁移到 native DOM's addEventListener

所以代替:

const domNode = document.querySelector('...');

google.maps.event.addDomListener(domNode, 'mouseover', (evt => {
  // handle mouseover
}));

你会做:

domNode.addEventListener('mouseover', (evt => {
 // handle mouseover
}));

在这两种情况下,侦听器的 evt 参数继续实现 DOM Event interface -- depending on the event type.

addDomListenerOnce备选方案

与上面类似,但增加了 once option。所以而不是:

google.maps.event.addDomListenerOnce(domNode, 'click', (evt) => {
  // handle clicks
});

你会做:

domNode.addEventListener('click',
  (evt) => {
    // handle clicks only once
  },
  { once: true }
);

return 类型已更改

请注意 google 的 addDomListener[Once] 都是 return a MapsEventListener

DOM 的 addEventListener 并非如此,returns void

因此,如果您之前存储了监听器 — 通常 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? 或者让浏览器的垃圾收集器为您分离监听器。


提示:addEventListener 也支持 passive 选项,可以 greatly improve performance.