Skip to content

Commit 92744e2

Browse files
authored
Merge pull request #212 from pyscript/dynamic-when-handling
Add call-out warning to describe handling events generated by dynamically created elements.
2 parents 2f03e7c + 2a16b99 commit 92744e2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/user-guide/events.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,41 @@ The decorator attaches the function to all elements matching the
3434
selector. If multiple elements match, the function is called for each
3535
one when its event fires.
3636

37+
!!! warning
38+
39+
The `@when` decorator only affects matching elements that exist
40+
_when the decorator is first encountered_. If you dynamically add
41+
matching elements _after_ `@when` is encountered, **they will not
42+
be affected**.
43+
44+
This reflects the browser-based capabilities that underpin
45+
the `@when` decorator. Ultimately,
46+
[JavaScript's `addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
47+
is called, and this also only affects elements that exist at the
48+
time of the call.
49+
50+
If you dynamically add new elements to the page, _you must also
51+
indicate an event is to be handled for that new element_. For
52+
instance, call `when` as a plain function, passing the new element
53+
directly:
54+
55+
```python
56+
from pyscript import web, when
57+
58+
59+
def my_handler(event):
60+
# Do stuff.
61+
...
62+
63+
# Dynamimcally add a new element to the page.
64+
el = web.button("Click me")
65+
web.page.body.append(el)
66+
67+
# Use when() as a plain function to attach the my_handler function
68+
# to the new button's click event.
69+
when("click", el)(my_handler)
70+
```
71+
3772
### Event types
3873

3974
You can handle any browser event. Common ones include:

0 commit comments

Comments
 (0)