diff --git a/folium/elements.py b/folium/elements.py index 89a6332a9..aa1dbd884 100644 --- a/folium/elements.py +++ b/folium/elements.py @@ -107,7 +107,7 @@ class EventHandler(MacroElement): _template = Template( """ {% macro script(this, kwargs) %} - {{ this._parent.get_name()}}.on( + {{ this._parent.get_name()}}.{{ this.method }}( {{ this.event|tojson}}, {{ this.handler.js_code }} ); @@ -115,11 +115,12 @@ class EventHandler(MacroElement): """ ) - def __init__(self, event: str, handler: JsCode): + def __init__(self, event: str, handler: JsCode, once: bool = False): super().__init__() self._name = "EventHandler" self.event = event self.handler = handler + self.method = "once" if once else "on" class ElementAddToElement(MacroElement): diff --git a/folium/map.py b/folium/map.py index b860956cc..d6d0a7483 100644 --- a/folium/map.py +++ b/folium/map.py @@ -24,7 +24,7 @@ class Evented(MacroElement): """The base class for Layer and Map - Adds the `on` method for event handling capabilities. + Adds the `on` and `once` methods for event handling capabilities. See https://leafletjs.com/reference.html#evented for more in depth documentation. Please note that we have @@ -33,8 +33,14 @@ class Evented(MacroElement): """ def on(self, **event_map: JsCode): + self._add(once=False, **event_map) + + def once(self, **event_map: JsCode): + self._add(once=True, **event_map) + + def _add(self, once: bool, **event_map: JsCode): for event_type, handler in event_map.items(): - self.add_child(EventHandler(event_type, handler)) + self.add_child(EventHandler(event_type, handler, once)) class Layer(Evented):