Friday, March 9, 2012

Custom Routing Events in Dart

Dart is a pretty cool little language—especially for something at version 0.07. But being at 0.07, there are numerous rough edges and things that just don't work. One of things that does not work is setting custom events on DOM elements. Tonight, however, I hope to do something a little different—custom router events.

I have the router in my Hipster MVC framework working to the point that I can initiate an app like so:

At some point in the future, I can either reflect on the function name (e.g. pageNum()) or extract the event name from the URL fragment. But, for now, I assume that a lack of a third parameter indicates that the calling context does not much care about the event, so I dump it into the "route:default" event space.

With an event name chosen, I need to dispatch the event. As I found last night, Dart cannot yet splat / apply arguments so I have to dispatch events the same way that I invoked the supplied callback. That is, I have to do it ugly:

As ugly it is to manually call the same function with different arity, it works.

With that, I know how I want to dispatch string-based events, and I already know from my main() entry point how I want to subscribe to them. All that remains is on property that will support dispatching events and subscribing listeners.

Before returning the listener list, I use the very nice, very confidentputIfAbsent(). If a key, like "route:page" does not exist, putIfAbsent() will add it with the value returned by the second argument—a simple builder method.

I also have to define RouterEventList and RouterEvent classes, but those are quite similar to the Collection event classes that I have previously defined.

I am quite pleased with that implementation. Dart's support for operator methods is a nice win here. I love the putIfAbsent() method on HashMaps. I plan on using that a lot as I continue to explore Dart.