New when-able when.
Description
DO NOT MERGE YET
A branch in which we work on the technical outcomes of the discussion over on #2203.
Changes
- Add illustrative unit tests.
Checklist
- [ ] I have checked
make buildworks locally. - [ ] I have created / updated documentation for this change (if applicable).
I can't quite work out if these unit tests will work if the handler is in a class. So I have added an example of that style. E.g. a class to hook a piece of UI up to some behaviour. Then the when would be something like:
(the below is really pseudocode, as not run at all)
from pyscript.web import page, body, div
class Mycontrol(object):
"""
This control creates a bit of UI and defines what to do when that bit of UI is interacted with
"""
def __init__(self, initial_values, parent=None):
self.parent = parent # so we can reach up to a parent structure to effect more complex actions
self.values = initial_values
self.widget = None # placeholder
def act(self,event):
"""
the UI got 'clicked' do something. called by @when
Probably replaced by the parent structure so more complex stuff can be done
"""
page.find("p").html("user clicked")
def get_widget(self):
" return the element to put in the UI "
mydiv = div("some title", classes="a-css-class", id="maindiv")
myp = p("click me", id="myp")
mydiv.append(myp)
# we could put the when in here but the element doesn't exist in the dom yet...
self.widget = mydiv
return mydiv
a = Mycontrol("stuff")
body.append(a.get_widget()) # can we add the when here ?
# or maybe a method of Mycontrol to add it once it exists ?
when(body.find("myp"), "click", a.act())
In an 'ideal' world the widget class would probably have been imported from a sep file (allowing more component like structuring)
One common use case might be to use when for modelling objects with possibly "events" e.g. Traits, Traitlets, Param in Python, and EventTarget in JS).
e.g. If I have some object that represents a car, I might have events for "started", "stopped" and "backfired" :)
car = Car()
@when(car, "started"):
...
@when(car, "stopped"):
...
@when(car, "backfired"):
...
Maybe I could also had a listener for all events on the car?
car = Car()
@when(car): # ? maybe not when at this point?
I'm not worried too much about the syntax @when(car.started) is fine, more that the syntax is consistent across our use of when for DOM elements. The car.started idea has the advantage of making the object writer explicit in declaring the events that it fires, but it does add a tiny bit more work when adding new events to an object. I know traits for one, made you do something similar when defining events.