Skip to content

Commit

Permalink
Implement the once method on Evented.
Browse files Browse the repository at this point in the history
  • Loading branch information
hansthen committed Nov 3, 2024
1 parent 8c2f753 commit 4983f45
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
5 changes: 3 additions & 2 deletions folium/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,20 @@ 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 }}
);
{% endmacro %}
"""
)

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):
Expand Down
10 changes: 8 additions & 2 deletions folium/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down

0 comments on commit 4983f45

Please sign in to comment.