10/29/2012

Bubbling in Enyo2, Part 3

Our first example was a simple event bubble from a button to a parent object.  The second example re-used the button object within two separate parents that handled the bubbled event differently.  Let's go one step farther.  This time the button's event will bubble all the way up the parent hierarchy.



In both previous examples, the event handler functions returned true when complete.
updateParagraph: function() {
  this.$.para.content = 'Not Blank Anymore';
  this.render();
  return true;
}

The return true on the last line tells Enyo to stop bubbling the event.  What happens if you omit return true, or instead return false?  Magic.  The event will keep moving up the kind hierarchy.  The next object up the hierarchy can capture the event.  If the parent wants to handle the event, they can.  If not, the event continues to the next parent until it runs out of objects or an object returns true.

Previously, the button kind became a re-usable component that was used in more than one place.  Now the event can be re-used as well.  Allowing the event to continue to bubble means any kind in the hierarchy can handle it.  It is important to note that the event has not been released to the environment but is still contained.  The bubbling process can not be used by any object outside the hierarchy chain.  The result is an organized form of event emission.

Let's modify our example from the previous example to use this principle:

The BubbleButton disables itself and sends the onUpdate event.  The BubbleParagraph changes its text and returns true.  The event stops here.  The BubbleDiv changes its text and end the function.  The BubbleDiv does not return true, so the event continues bubbling up.

The parent of the BubbleDiv is the App.  The App also has a handler for an onUpdate event.  The App takes the event and runs with it.  The App's onUpdate event calls its increaseDivCount function.  The function increases the App's internal divCounter and displays the new text.  At this point, the function returns true ending the event's upward journey.

One of my favorite features of the Enyo framework is the Event bubbling system.  Revisiting the witches from Part 1, I wonder if MacBeth would have had a different ending if they had stuck to Enyo instead of bubbling potions.


Previous parts
Bubbling in Enyo, Part 2
Bubbling in Enyo, Part 1