Skip to content

Commit 1f2d67b

Browse files
hansthenConengmo
andauthored
Implement the once method on Evented. (#2023)
* Implement the `once` method on Evented. * Update folium/elements.py Co-authored-by: Frank Anema <[email protected]> * Update folium/map.py Co-authored-by: Frank Anema <[email protected]> * Update folium/map.py Co-authored-by: Frank Anema <[email protected]> * Update folium/map.py Co-authored-by: Frank Anema <[email protected]> --------- Co-authored-by: Frank Anema <[email protected]>
1 parent f2ec195 commit 1f2d67b

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

folium/elements.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,19 +107,20 @@ class EventHandler(MacroElement):
107107
_template = Template(
108108
"""
109109
{% macro script(this, kwargs) %}
110-
{{ this._parent.get_name()}}.on(
110+
{{ this._parent.get_name()}}.{{ this.method }}(
111111
{{ this.event|tojson}},
112112
{{ this.handler.js_code }}
113113
);
114114
{% endmacro %}
115115
"""
116116
)
117117

118-
def __init__(self, event: str, handler: JsCode):
118+
def __init__(self, event: str, handler: JsCode, once: bool = False):
119119
super().__init__()
120120
self._name = "EventHandler"
121121
self.event = event
122122
self.handler = handler
123+
self.method = "once" if once else "on"
123124

124125

125126
class ElementAddToElement(MacroElement):

folium/map.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
class Evented(MacroElement):
2525
"""The base class for Layer and Map
2626
27-
Adds the `on` method for event handling capabilities.
27+
Adds the `on` and `once` methods for event handling capabilities.
2828
2929
See https://leafletjs.com/reference.html#evented for
3030
more in depth documentation. Please note that we have
@@ -33,8 +33,14 @@ class Evented(MacroElement):
3333
"""
3434

3535
def on(self, **event_map: JsCode):
36+
self._add(once=False, **event_map)
37+
38+
def once(self, **event_map: JsCode):
39+
self._add(once=True, **event_map)
40+
41+
def _add(self, once: bool, **event_map: JsCode):
3642
for event_type, handler in event_map.items():
37-
self.add_child(EventHandler(event_type, handler))
43+
self.add_child(EventHandler(event_type, handler, once))
3844

3945

4046
class Layer(Evented):

0 commit comments

Comments
 (0)