From 4983f45f9e3f9529f0d81d55c7cf5f0a36da8f5b Mon Sep 17 00:00:00 2001 From: Hans Then Date: Sun, 3 Nov 2024 08:23:09 +0100 Subject: [PATCH] Implement the `once` method on Evented. --- folium/elements.py | 5 +++-- folium/map.py | 10 ++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/folium/elements.py b/folium/elements.py index 3d4498517..c87a648ae 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=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 26a333ca1..cde7b6984 100644 --- a/folium/map.py +++ b/folium/map.py @@ -25,7 +25,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 @@ -34,8 +34,14 @@ class Evented(MacroElement): """ def on(self, **event_map: JsCode): + self._add(False, **event_map) + + def once(self, **event_map: JsCode): + self._add(True, **event_map) + + def _add(self, once, **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):