简体   繁体   中英

How to check if event already exists for marker in google maps api v3

I have created a marker and attached click event listener to the marker. However, I would like to check if the click event has been already attached to the marker and if not, attach the click event listener.

// If no click event listener, then attach the listener
google.maps.event.addListener(marker, 'click', function() {
  infowindow.open(map, marker);
});

I can however check with a custom flag in the marker object as:

// If no click event listener, then attach the listener
if (! marker._isClickEventBound) {
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
    marker._isClickEventBound = true;
  });
}

The same code is executed during the addition of new marker and editing the marker. I just wanted to know if there is any other way rather than adding a flag ?

Adding a flag is actually fine.

Apart from that, google.maps.event.addListener returns you an event object. You can keep track of all event objects you've added to also clean up marker events if needed...

hasListeners returns a boolean:

google.maps.event.hasListeners(marker,'click')

also works on the map itself:

google.maps.event.hasListeners(map,'idle')

丑陋的黑客将删除所有听众并再次附加它。

google.maps.event.clearListeners(map, 'click');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM