While writing the Events chapter in Dart for Hipsters, I got to thinking about the square brackets operator for the
Element#on
getter. I know that it works for the existing events, such as click events:main() { Element el = document.query('#status'); el. on['click']. add((event) { el.style.textDecoration = 'underline'; }); }Normally, I would write the above using the
click
getter: el.
on.
click.
add((event) {
el.style.textDecoration = 'underline';
});
The square bracket operator approach allows for some run-time variance. I could also see adding the same event handler to a bunch of different events by iterating over the event names as strings.Anyhow, with the square bracket version in place, when I load the page and click on the previously not underlined "Status!" header:
It is now underlined:
This got me to thinking about custom events. Since this is a "status" element, perhaps I can use this to listen to custom "status" events through the square brackets operator:
main() { Element el = document.query('#status'); el. on['status']. add((event) { print("event received: ${event.type}"); el.style.color = event.type; }); }I try to dispatch this event by calling
dispatch()
on the event listener list returned by the square brackets: Event green_event = new Event('green');
el.
on['status'].
dispatch(green_event);
Only nothing happens.Firing this up in type checking mode, I am greeted by an exception indicating that the event type (the string
"green"
in this case) needs to be known by the event listener list:Exception: 'dart:htmlimpl': Failed assertion: line 23081 pos 12: 'evt.type == _type' is not true. Stack Trace: 0. Function: 'AssertionError._throwNew@127eafe4' url: 'bootstrap' line:552 col:3 1. Function: 'EventListenerListImplementation.dispatch' url: 'dart:htmlimpl' line:23081 col:12 2. Function: '::main' url: 'file:///home/cstrom/repos/dart-book/book/includes/events/main.dart' line:36 col:13Dang.
Ah well, on the bright side, that is one less section that I need to write for the book.
Day #308
No comments:
Post a Comment