Monday, August 5, 2013

Custom Events in Dart


I need to decide how to approach the rewrite of the events chapter in Dart for Hipsters. I think mostly the events chapter needs to be renamed the “streams” chapter and get a streams makeover. I think that most the approach and content can stay, though I may want to touch on some of the nicer features of streams (like iterable).

Actually, re-reading the chapter, I see that it is fairly short, which should make my job easier—it should also give me ample time to explore streams if I want to. The big thing that I notice is how much nicer streams are conceptually. The current edition of the book features many word gymnastics to explain ElementEvents, Events, Event and my favorite, EventListenerList. Streams even make it easier to generate custom events, which is a big part of the chapter.

One thing that I do not quite understand about Dart events are attaching custom events to HTML elements. The Events class documentation provides an example of listening for these events. It defines a “generator” class which includes a single static property, dataEvent
class DataGenerator {
 static EventStreamProvider<Event> dataEvent =
   new EventStreamProvider('data');
}
Since dataEvent is an EventStreamProvider, I can get a stream with the forTarget() method:
      DataGenerator.
        dataEvent.
        forTarget(element).
        listen((data) {
          print(data);
        });
But how do I generate a “data” event?

Hrm... perhaps this is one of the uses of the dispatchEvent() method in the Element class?

Indeed it is. When I dispatch a new “data” event:
element.dispatchEvent(new Event('data'));
Then the listener for my custom even prints:
Instance of 'Event' 
Well, that was easy enough.

For some reason, I still feel as though I have a gap somewhere in my understanding of events and streams. It is possible that I am over-thinking things. Since forTarget() produces a stream, I want something that will let me place objects (events or otherwise) directly on the stream. I want a StreamController or some other equivalent. But this might be me over-thinking—the dispatchEvent() method and forTarget() method seem to be a closed loop for working with HTML element streams in Dart.

Bah. I still feel like I am missing something somewhere. Hopefully it is not that big a gap that it makes the events chapter less than it could be.

Day #834

No comments:

Post a Comment