Monday, January 4, 2016

Event handling in Polymer.dart

So, I finally managed to get all the basic functionality from the "Polymer and Dart Codelab Admin Console" into my fork. The last step was to implement a set of methods in the superclass elements. These methods are called in response to interaction with the elements such as clicking on buttons, etc.

As a bit of background, I decided it would be a worthwhile exercise to "abstract?" out as much of the code as possible from the Codelab elements into more general superclasses containing only "title" and "description" fields, and make use of these superclass elements in the Code lab.

It should be noted that my design is a bit quirky and is based on a deprecated version of Polymer.dart. Particularly, my custom elements subclass other custom elements, which is not possible in the latest Polymer.dart. Another aspect of my design is just plain wrong: I instantiate superclass elements *inside* of my subclass elements! For example:

<codelab-element attributes="editing" extends="item-element">
    <item-element>
        <!-- codelab property -->
        <!-- codelab property -->
    </item-element>
</codelab-element>

This allows for the insertion of codelab properties into <item-element> using the <content> tag in <item-element>. Polymer.dart doesn't complain, and Dartium is happy to render the result without error.

A challenging aspect of using polymorphism turned out to be getting the subclass methods to be called in response to events in the superclass elements. For example, when the "submit" button is clicked in <item-form> it's necessary that the CodelabElement::submit() event handler is called so that any CodelabElement-specific operations are performed before handing execution off to ItemElement::submit(). Naturally, if <item-element> calls "submit()", ItemElement::submit() is going to be executed. Not what we want.

So it finally occurred to me to add an ItemElement::submit() method. This then fires a new event, 'itemupdated', which is caught by <codelab-element> because it happens to be the parent.

So we have the kind of ridiculous situation where a subclass instance is a parent of the superclass instance. But it works.

While walking, today, it occurred to me that the design could be a bit cleaner by firing events directly from the superclass element which would be caught by the subclass parent, rather than the superclass. But it doesn't turn out to be possible to do this, as far as I can tell.</codelab-element></item-element></item-form></item-element></content></item-element>

No comments:

Post a Comment