Marc Hughes


Home
Blog
Twitter
LinkedIn
GitHub
about
I am a developer from a bit west of Boston.

Bubbling events in data models

14 Apr 2009

I've been using moccasin for a bit now on a smallish project.  One of the cool things it does is give you a sort of event bubbling in your datamodel.  While moccasin is a very specific framework for a very specific sort of application, the more I think about it, the more I like the bubbling-events in the data model part as a general solution to a wider variety of problems.

Let's look at a very simplified example that illustrates the general idea (actual mocasin implementation varies quite a bit from this).  Imagine this code...

public class PizzaModel
{
  [Bindable] public var sauce:PizzaSauce;
  [Bindalbe] public var size:Number;
}

...

[Bindable] public class PizzaSauce { public var name:String; public var displayColor:uint; }

...

public class PizzaView extends UIComponent { public function setPizza( pizza:PizzaModel ) { pizza.addEventListener(ModelChangeEvent.MODEL_CHANGE, onModelChange); }

protected function onModelChange(event:ModelChangeEvent):void { switch( event.property ) { case "size": // the pizza size changed, handle that.

case "sauce/displayColor": // the sauce color changed, handle that.

default: // some property that we can't incrementally // update changed, handle that...

} } }

We have some kind of model object, let's call it the PizzaModel.

That model has a property, that itself is some kind of complex object.  Lets call that property sauce, and the type will be called PizzaSauce

Now, we have some kind of view object.  Let's call it the PizzaView.

A normal way to implement something like this would be to have the pizza view listen to events on both the pizza object and it's sauce object. Or it could manually set up some change-watchers that watched the hierarchy to the required properties.

That's all fine and dandy until we get to more complex object hierarchies. What if we had an arraycollection of toppings and we needed to know when individual properties of those toppings changed? Now, we'd have to listen to yet another type of event.

And what happens of those toppings themselves had lists of ingredients we wanted to listen to, suddenly the event chain is getting pretty gnarly to manage.

If we had some kind of magical bubbling model event, we'd only have to listen at a single location, as shown above. Especially if there was an expressive way of identifying what changed.

How might something like this be implemented?

Mocassin does it by having a meta-data model that wraps the actual data model and provides this extra functionality.

Another way would be to force the data model objects to all extend from a common superclass (I believe earlier versions of Moccasin did just that)

Someday, I'd like to explore either creating a general purpose framework for this or extracting it from Moccasin. I'm blogging about it hoping someone might do it before I get a chance ;)