Skip to content

Commit

Permalink
Implement the once method on Evented. (#2023)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
hansthen and Conengmo authored Nov 17, 2024
1 parent f2ec195 commit 1f2d67b
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: bool = 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 @@ -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
Expand All @@ -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):
Expand Down

0 comments on commit 1f2d67b

Please sign in to comment.