Bubbling in Enyo2, Part 1

"Bubble, bubble, toil and trouble" cry the witches of Macbeth.  Clearly, they never tried using Enyo 2 as their JavaScript framework or it would have been "Bubble, bubble, yahoo!".  The event bubbling system is one of the features that makes Enyo 2 feel so powerful.

The bubble method allows events to be sent up the object hierarchy.  This is not the same thing as bubbling up the DOM.  The object structure that is in memory can be similar to the DOM, but the process will only work against the object hierarchy.  Changes to the DOM will need to be rendered separately.

Events can range from UI interactions, such as a tap, to custom events that are fired manually.  Events will bubble starting at the originator and will continue to bubble until an object handles it and returns true, or if there are no more objects.  Events travel in the form of "oneventName", such as "ontap" or "onspecialEvent".

An object in Enyo defines the events it can handle with the "handlers" property.  An Enyo object that responds to a tap event will have an "ontap" handler.  The handler property contains the name of the function to call when that event is handled.  The result is that event and event handling are separated   Event and event handling being defined arbitrarily provides a great method for decoupling objects and encouraging encapsulation.

Let's take a look at a simple example (http://jsfiddle.net/dposin/nY2AD/):

This code uses 2 Enyo kinds to create a page with a "Blank Paragraph" and a button.  Enyo 2 uses the term kind in a way similar to class or type.  A kind is a definition of an object that can be instantiated.  The button in the example is a new kind called BubbleButton.  It uses the enyo.Button kind as a parent.  The button calls the tapped function when it handles an ontap event.  Since ontap is a pre-defined event, the button will fire the ontap event when the user presses it with a finger or mouse click.

The tap sends an onUpdate event up it's container hierarchy.  The button's involvement stops here.  The App kind captures the onUpdate event next.  The event stops moving until the App kind is done and returns a boolean value.  The App kind calls its own updateParagraph function. The function changes the App's content property to "Not Blank Anymore".  The change is then rendered for the user to see.  The updateParagraph function returns true which indicates the event stops there.  The function could return false, or nothing, which would send the event up to the next object.

The example shows two kinds with their own functionality that still interact.  The important point is that neither kind is aware of the other one's existence.  The bubbling process provides a mechanism for anonymous communication between the two.

In Part 2 we will expand the example to show how this mechanism can encourage code re-use.