Reuse … Your Brain

Components were supposed to save us; they were the silver bullet that would make code reuse actually work. The problem with reusing code is that it takes at least three times as much work to make a component that works in all cases rather than just the ones the component author had in mind, and no one wants to put the work in unless they are getting paid.

The fun part of components is figuring out the best level of encapsulation and making a piece that fits nicely into that spot. Testing, debugging, documentation, and validation are not (for most people) the fun parts. for components to be useful in more than one context, they have to be internally and externally consistent, they have to handle attribute changes in all possible combinations, and they have to handle external error conditions at every possible point. Software libraries and SDK’s distribute themselves as classes and components, and they make applications possible. For the infrastructure organizations and component vendors, this is their business.

Components built within organizations do not have the support of paying users, and so they tend not to have the fit and finish of their commercial brethren. A commenter named Tim put it well in a discussion about Agile/XP and reuse:

The first time you have to pay for it to be coded,
The second time you have to pay for it to be reusable,
The third time it’s free.

With all due respect to Agile and XP, I err towards the other end of the spectrum: I like to build software clean enough that I am not embarrassed to have others use it. I want it so obvious that I will understand it quickly when I come back to it later. I like building well-rounded components that will survive a little transplantation or changes in usage. I like to take the time to make classes that know how to clone, clear, deep-copy/assign, and test equality. In other words:

Treat Yourself As You Would Have Others Treat You

Nevertheless, managers see a component named DataManager and assume (or at least hope) they can reuse it anywhere their design calls for a data manager. They don’t want to “waste” the effort spent building it the first time. Here is when intuition fails us all: we talk of “building” software instead of “composing” it. Software is ideas made manifest (albeit in a structure that judges those ideas against a very solid and unforgiving reality).  Software is not an engine where the number of cylinders is fixed. However, composing a better component is easier than building a second house. It’s often impossible to rebuild a component exactly the same as its original because the composer/author/developer/coder can’t stop themselves from improving their idea.

Besides running the same code in different environments, the best reuse is reusing experience. Experience grows all the time (and grows faster from bad outcomes). Rather than looking at components as commodities that remove the need for experienced developers, look at components as the steps that developers can stand on to see farther.

Hierarchical Data Grids

I recently had cause to create a grid that showed rows with parent, child, and grandchild rows. Each generation’s text is indented to show the relationships, and rows with children have a plus or minus to show and hide them. While the AdvancedDataGrid can create virtual parent rows for unique values, it is not built to show actual parent and child rows.

Sample Application with source: http://flex.santacruzsoftware.com/HierarchicalDataGrids/

One way to manage parent-child relationships is to store all the raw data in one list and use a different list to display the data. Each row must indicate if they are parents and, if so,  are their children are visible. In my case, those flags were already present in the grid’s data row object (ReportRow), alternatively, one could use external lists and messages to hold this information (see The Ultimate Checkbox List Pattern). The row objects have a collection of child rows as a property, and a value that indicates what generation (level) they are.

public function onExpand(event : Event) : void
{
	this.refreshExpandedItems();
}

public function refreshExpandedItems() : void
{
	var prevSelection : Object = reportGrid.selectedItem;
	var prevScrollPosition : uint = reportGrid.verticalScrollPosition;

	this.reportData.refreshDisplayList();

	reportGrid.selectedItem = prevSelection;
	reportGrid.verticalScrollPosition = prevScrollPosition;
}

The grid’s ItemRenderer shows an expansion icon (e.g. “+” and “-“), handles indenting the text to show each row’s level, and throws a bubbling event whenever the user clicks the expansion icon. The dataChange method (or the overriden data mutator) handles indentation as well as which rows should have expansion icons.

private function onDataChange(event : Event) : void
{
	if (this.data != null)
	{
		var theRow : ReportRow = this.data as ReportRow;

		nameLabel.text = theRow.name;
		nameLabel.x = 20 + (theRow.level * INDENT_PER_LEVEL);

		if (theRow.children.length > 0)
		{
			expansionLabel.visible = true;

			if (theRow.isExpanded)
				expansionLabel.text = "-"
			else
				expansionLabel.text = "+"
		}
		else
			expansionLabel.visible = false;
	}
}

private function onExpansionClick(event : Event) : void
{
	var theRow : ReportRow = this.data as ReportRow;

	theRow.isExpanded = !theRow.isExpanded;

	var expandEvent : ExpandEvent =
		new ExpandEvent(ExpandEvent.EXPAND_PARENT, true);
	expandEvent.row = theRow;

	this.dispatchEvent(expandEvent);
}

When this event (or some other application code) marks a row as newly expanded or an expanded row as collapsed, the data object refreshes the entire display list by emptying it and iterating through the entire raw-data list and copying each parent and, if expanded, its children to the display list. Depending on one’s needs, one can recursively check the children for nested grandchildren, etc.

I created a separate class to hold and manage the data as a grid-specific model. The container holding the grid creates an instance of the data object, and that object not only manages the raw and display lists and also parses the result from a server into grid-specific row objects. It also has a bindable array collection of row objects to display; this is what the grid uses as its displayProvider.

While Flex’s update event model will likely avoid thrashing the display, one can use displayList.disableAutoUpdate() or binding with an explicit event and dispatching an explicit event to ensure that the DataGrid refreshes only once after the display list changes

[Bindable(event="displayListChange")]
public var displayList : ArrayCollection = null;

public function refreshDisplayList() : void
{
	displayList.removeAll();

	for(var counter : uint = 0; counter < rawDataList.length; counter++)
		addRow(rawDataList.getItemAt(counter) as RowData);

					//	signal that all changes are complete
	this.displatchEvent(new Event("displayListChange"));

					//	nested function
	function addRow(aRow : RowData, generationNumber : uint = 0) : void
	{
				//	put any client-side filtering tests here

		aRow.displayIndentLevel = generationNumber;
		displayList.addItem(aRow);

		if (aRow.isExpanded)
		{
			var theChildRow : RowData;

			for(var childCounter : uint = 0; childCounter < aRow.children.length; childCounter++)
			{
				theChildRow = aRow.children.getItemAt(childCounter) as RowData;

				addRow(theChildRow, generationNumber + 1);	//	recursive
			}
		}
	}
}

Sorting and Filtering

The raw data list’s sort function needs to sort without breaking the relationship between each row, its parent, and its children. One can either sort the highest level and leave the descendants unsorted; one can sort each of the generations relatives to its siblings. To filter display rows, simply omit rows from the display list rather than using a filter function on either the raw data list or the display list.

Performance

displayList.addItem(aRow) inserts a reference to the row object in the rawDataList ; it does not create a copy of the actual data. Moving a few hundred references around does not take a lot of time. Compared to redrawing the grid itself, managing the references is instantaneous.

Paging Hierarchical Data

Many Flex applications using grids show only part of the total data set (no one actually wants to see 10,000 rows). In this vein, one might want to load the children of a row if and only if the user expands it. The rawDataList will retain any children once downloaded, so repeated expansion and collapse will not overload the server, but getting the child rows the first time requires a specific protocol.

In my case, the server allowed me to get the report data passing flag indicating ParentsOnly (which gets only the top-level rows) or criteria to specify one particular top-level entity (which I used without the ParentsOnly flag to get the descendants). As I don’t get the children until needed, the item renderers need an isParent property in each item (to replace the test theRow.children.length > 0) so knows they whether to show the expansion icon at all.

The EXPAND_PARENT event listener checks the event’s ReportRow isExpanded and children == null If both are true, it has to retrieve the children from the server, insert them into the ReportRow.children property, and then call refreshExpandedItems(). This requires at least one asynchronous step, so the COMPLETE listener (as well as the fault handler) needs to clear any “Please Wait” messages. If the row is collapsing or already has its children, the listener can simply call refreshExpandedItems().

Or That

Coming from Delphi, I use properties for everything. I even create protected and private properties for use inside a class:  they are good idea, so I don’t limit them to public interfaces.

A new wrinkle I’m dealing with is bound properties that have default values. For example, a Button sub-class that has a default caption but also has a public property that the user can bind to some other value. A normal property with a default would look like this:

private static const DEFAULT_ENABLED_CAPTION : String = "Click me!";

[Bindable]
public var enabledCaption : String = DEFAULT_ENABLED_CAPTION;

One can bind this property to a child component in an MXML component or use it in the commitProperties() method of an ActionScript component. It acts as a proxy for the “real” property, and allows different values based on state (e.g. enabled and disabled captions based on the enabled property).

When one uses binding to set values, if the object configuration is null or the property enabledCaption is blank at any time, the property loses its default value and does not get a valid replacement.

    <components:MyButton enabledCaption="{configuration.enabledCaption}"
                  disabledCaption="{configuration.disabledCaption}" />

Assuming that one does not want to allow an empty string (or null), some small changes to the accessor and mutator can handle these automatic assignments by the binding mechanisms:

public static const CAPTION_CHANGE : String = "captionChange";
private static const DEFAULT_ENABLED_CAPTION : String = "Click me!";

[Bindable(event="captionChange")]
public function get enabledCaption() : String
{
    if (_enabledCaption== "")
        return DEFAULT_ENABLED_CAPTION;
    else
        return _enabledCaption;
}
public function set enabledCaption(value : String) : void
{
    if (value == null)
        _enabledCaption = "";    //  strings should not be null

    if (_enabledCaption != value)
    {
        _enabledCaption = value;
        this.dispatchEvent(new Event(CAPTION_CHANGE));
    }
}
private var _enabledCaption : String = DEFAULT_ENABLED_CAPTION;

No matter how many times the binding mechanism updates the component property (i.e. calls the mutator), the accessor will return the default value unless the binding (or some other code) sets the value to a non-null, non-blank string.

Teach Me, Bicycle-Repair Main

I finally have my car fixed. It is a 2005 Prius (second series) and would sometimes fail to allow the headlights to go into low-beams only. My mechanic could not find the cause and sent me to another mechanic. They spent several hours and determined that I needed a new (expensive) headlight switch, which they would special-order.

They estimated one (1) hour installation and I arraigned to bring the car in before work to wait while they installed it. When I arrived, they said it would be done in 1.5 hours. Hmmm.

Two hours later, I was on my way (late to my morning meeting). They cheerfully explained that they had never done this type of switch before, and that I would not have to pay for the extra time it took them. I snarled under my breath at their presumption that I should be happy that I did not have to pay for them being late.

Until I realized that, as software developers:

  • We too give estimates based on the best-case scenario (and we believe it ourselves)
  • We too have our clients/employers pay for us to learn new things
  • And we do charge them if things take us longer then we said they would

Advanced Topics Using a Message-Based Checkbox List Pattern

Fifth in a series of five. This blog entry is part of my article in the Flash and Flex Magazine

The checkbox pattern described in the previous four blog entries allows a lot of flexibility and subtly in your applications. This post covers some of the issues I’ve dealt with, a bit of philosophical and aesthetic musing, and an example application.

Setting The Manager’s Event Listeners

Setting the  list manager’s listeners in the startup event cycle is tricky. In general, I use addEventListener() in the creationComplete event for listeners on the form, however this does not work if the checkbox list or grid is a design-time  child on the form (e.g. it’s in the MXML or created by createChildren()). By the time the creationComplete event fires, the grid has already initialized and all the item renderers have dispatched their first AmISelected events, which receive no answers because the listener is not set up yet.

Register amISelected listeners in the initialized event.

Messages vs. Interfaces

A different way of loosely linking parts of a system is interfaces. One could pass an instance of an interface that had toggleSection and amISelected methods to an item renderer. The class of that instance could be anything; the caller would not know who was executing the method and the method would not know who was calling it. Passing an instance more than one layer deep, however, creates a loosely-linked chain, and the more links in a chain, the more fragile it is.

Every container between the list manager (e.g. the form or component’s top-level container) would have to pass the instance on to every child that could hold it (probably because the children implemented an interface themselves). Components that had no interest in this interface would still be responsible for passing it on.

Messages, however, are already part of every UIComponent’s interface (because it implements IEventDispatcher): they allow listeners to hook into the messages; the message framework moves the event objects through the containership model; and the event objects themselves can change without changing the interface.

Message-Based MVC

The Ultimate Checkbox List Pattern resembles a Model-View-Controller: the item renderer would be the view; the list of selected items would be the model; and the event listeners on the list manager would be the controller. In an classc MVC pattern, the controller would push the changes into the view, and therefor would need to know how it worked (i.e. what method to call or property to push). The UCLP has the model pushing a change notification into a generic listener in the view, and then the view pulls the change information from the model; the module (and the controller, for that matter) do not know anything about the view besides a reference to the view’s notification listener.

Matching By Value vs. Matching By Reference

As shown in the sample application, one can use a more robust test to see if a Thingie is in the selected list than simply checking getIndexOf(). While the “thingie” might be a complex Value Object, this pattern also lends itself to simple data objects that might be dynamically created to wrap one or two column values. In this case, the object itself might not come from a global (i.e. singleton) store; one might have several simple instances that represent the same values, but not the same instances in memory.

For example, in the sample application (which has View Source)

 

Sample Message Based Checkbox List Application
click for SampleMessageBasedCheckboxListApplication

 

the AmISelected method checks if the data is selected, not just if the Thingie instance in the event is also on the list. Actually, the original version had a middle section that used api.business.gov to show a grid that was not even Thingie objects, but it has no crossdomain.xml, so…

Use this pattern to support your needs: if you have different representations of the same concept and you want to select or de-select the concept, then make the AmISelected check if the concept is on the list; if the objects in question are references to singleton objects on a central list (e.g. value objects), then check if the object itself is referenced by the list.

Let Me Know

Let me know what you think of this pattern. Let me know how I could explain it better. How have you improved it ?

Multiple States and Multiple Dependencies Using Message-Based Checkbox Patterns

Fourth in a series of five. This blog entry is part of my article in the Flash and Flex Magazine

While a basic Ultimate Checkbox List Pattern uses only a single Boolean value – e.g. isSelected – its questioning event can allow more than just one answer: in addition to finding out if a row is selected (e.g. checking a checkbox), a questioning event can determine if a specific list item is visible or enabled at all. For example, the current user might not have rights to see a particular value; the page might have a terse or verbose option; some criteria might be selectable based on a separate criteria selection; or a set of items might have a maximum number of selections.

Like the selected state, the enabled state of a list item could be embedded in the item data itself, however one can choose to extend the Ultimate Checkbox List Pattern to. As each change in the list (or its proxy) makes every item check its state (see Multiple Views Using a Message-Based Checkbox Pattern), disabling any or all items is as easy as disabling one (remember that only visible items have item renderers with listeners which check state).

public class ThingieEvent extends Event
{
    public function ThingieEvent(...)
    {
        ...
    }
    public var thingie : Thingie;
    public var isSelected : Boolean = false;
    public var isEnableded : Boolean = true; // new flag public var notificationListener : Function;
}

The item renderer registers a listener the first time it checks the current item’s state by adding it to the questioning event:

...
        var theEvent : ThingieEvent = new ThingieEvent(IS_THINGIE_SELECTED, true);
        theEvent.thingie = data as Thingie;
        theEvent.notificationListener = this.onExternalThingieChange;
        this.dispatchEvent(theEvent);
        isThingieSelectedCheck.selected = theEvent.isSelected;
        isThingieSelectedCheck.enabled = theEvent.isEnabled;
...

And whenever the item renderer’s notification listener indicates something external changed, it will check the state of the specific data currently in the item renderer.

    private function onExternalThingieChange(event : Event) : void
    {
        var theEvent : ThingieEvent = new ThingieEvent(IS_THINGIE_SELECTED, true);
        theEvent.thingie = data as Thingie;
        this.dispatchEvent(theEvent);
        isThingieSelecctedCheck.selected = theEvent.isSelected;
        isThingieSelecctedCheck.enabled = theEvent.isEnabled;
    }

On the list manager side, the first time the item renderer asks for a selection status by dispatching a questioning event, the list manager adds the notification listener (if present) using weak references. It can add the callback as a listener directly to the data list (e.g. ArrayCollection), or it can add it to a separate IEventDispatcher object in order to proxy events explicitly from multiple sources (e.g. signal a change when the _thingieList changes and when the user changes between “terse” to “verbose”).

    private var _thingieList : ArrayCollection = new ArrayCollection();
    private var _thingieListProxy : EventDispatcher = new EventDispatcher();
      ...
        _thingieList.addEventListener(CollectionEvent.COLLECTION_CHANGE, onThingiesChange);
        context.addEventListener(Event.STATE_CHANGE, onThingiesChange); // something else that requires a change-check
      ...

    private function onThingiesChange(event : Event = null) : void
    {
        _thingieListProxy.dispatchEvent(new Event(Event.CHANGE));
    }

    private function onIsThingieSelected(event : ThingieEvent) : void
    {
        event.isSelected = (_thingieList.getIndexOf(event.thingie) != -1);
        event.isEnabled = (context.currentState == SELECTABLE_STATE) && (_thingieList.length < MAX_SELECTED_THINGIE_COUNT);
        if (event.notificationListener != null)
            _thingieListProxy.addEventListener(Event.CHANGE, notificationListener, false, 0, true);
    }

If the onThingsChange event carried information, it would link the listener and the dispatcher more tightly than we want. Using a generic Event with the type Event.CHANGE (the simplest possible notification) insures that the dispatcher can send that notification for any reason it wants; it is not restricted by any required or expected event parameters.

For those who like sequence diagrams:sequence diagram for multiple=

(Update: sample application in the final installment)

Multiple Views Using a Message-Based Checkbox Pattern

Third in a series of five. This blog entry is part of my article in the Flash and Flex Magazine

The previous post showed how one can have an item renderer communicate with one of its containers to set and retrieve the selected (e.g. checked) state of the item renderer’s data. If, however, the same data (and its selected state) appear in more than one view, one needs to add another set of notifications to the pattern.

If something other than a particular item renderer changes the values in the thingieList, the item renderer needs to know to change the checkbox status. Rather than iterating through the children of the DataGrid or List to find all the ItemRenderers to tweak them, we can have sort of a “push” notification: the item renderer passes a listener function to the list manager the first time it asks for an item’s selected status, and external changes call that listener. To make things as generic as possible, the listener does not expect any specific type of event (i.e. the event does not contain information about the change); it simply checks its own status whenever it’s called.

This combination seems complicated, but it’s built on what we’ve done before:

  • The view dispatches an AmISelected event with a reference to its event listener function in it.
  • The list controller adds the event listener
  1. Something changes the list
  2. The list dispatches a CHANGE (or COLLECTION_CHANGE) event to all the listener functions
  3. The view listener functions dispatch an AmISelected event (without a listener reference in it)
  4. The list controller received the AmISelected event object and sets its .isSelected property based on the list
  5. The item renderer checks the .isSelected property and updates its display based on the answer


This causes a lot of events that don’t actually find any changes (i.e. every item renderer whose data have not be selected or deselected), however the cost for these events is low and the value of simplicity is high.

The item renderer registers a listener the first time it checks its data’s status:

 ...
        var theEvent : ThingieEvent = new ThingieEvent(IS_THINGIE_SELECTED, true);
        theEvent.thingie = data.thingie;

        theEvent.notificationListener = this.onExternalThingieChange; this.dispatchEvent(theEvent); // ---- listeners execute here

        isThingieSelectedCheck.selected = theEvent.isSelected;
 ...

And the item renderer’s listener function checks the status

private function onExternalThingieChange(event : Event) : void
{
    var theEvent : ThingieEvent = new ThingieEvent(IS_THINGIE_SELECTED, true);
    theEvent.thingie = data.thingie;
    this.dispatchEvent(theEvent);
    isThingieSelectedCheck.selected = theEvent.isSelected;
}

On the list manager side, it adds the callback function (if present) as a listener using weak references. It could add the callback as a listener directly to the data list or to a separate IEventDispatcher object if it was going to fire events explicitly

private function onIsThingieSelected(event : ThingieEvent) : void
{
    event.isSelected = (_thingieList.getIndexOf(event.thingie) != -1);

    if (event.notificationListener != null)
        _thingieList.addEventListener(CollectionEvent.COLLECTION_CHANGE, event.notificationListener, false, 0, true);
}

By adding one notification, changes to the selection list automatically update all items whether they are visible or become visible later, so the user can can modify or clear the list without tight coupling with all the other views that add and remove items.

(Update: sample application in the final installment)

The Ultimate Checkbox List Pattern

Second in a series of five. This blog entry is part of my article in the Flash and Flex Magazine

A common task is to put checkboxes into a list or grid. Instead of adding Boolean property values to the dataProvider items, the Ultimate Checkbox List Pattern leaves the display item alone (e.g. a pure value object) and uses membership in a separate list of items to indicate if an item is selected (checked). Often, this list of selected rows itself is very useful. Standard ActionScript events communicate between the item renderers (with a checkbox) and a container object or the form itself acting as a controller for the selected list.

The key to this pattern is anonymous communication: the list controller does not know what components are sending messages asking if this or that object is or is not selected, and the view (i.e. an ItemRenderer) does not know who is listening and answering its questions. They communicate using a custom event that adds a reference to the item, and a Boolean: isSelected. For example,

public class ThingieEvent extends Event
{
    public var thingie : Thingie;
    public var isSelected : Boolean = false;
    public var notificationListener : Function;
}

Changing the Selected State
The ItemRenderer sends an event when user interaction with its checkbox changes the selected state:

 ...
        var theEvent : ThingieEvent = new ThingieEvent(THINGIE_SELECTION, true);
        theEvent.thingie = this.data.thingie;
        theEvent.isSelected = thingieCheckBox.selected;
        this.dispatchEvent(theEvent);
 ...

The list manager might handle the event like this:

    private function onIsThingieSelected(event : ThingieEvent) : void
    {
        var existingIndex: int = _thingieList.getIndexOf(event.thingie);
        if (event.isSelected != (existingIndex != -1))
        {
            if (event.isSelected)
                _thingieList.addItem(event.thingie);
            else
                _thingieList.removeItemAt(existingIndex);
        }
    } 

    private var _thingieList : ArrayCollection = new ArrayCollection();

Getting the Selected State
When an ItemRenderer initializes itself, it needs to know if it should set the checkbox.selected attribute based on the data. It needs to ask someone outside itself if the current item should be checked. Rather than have the list manager add event listeners to every ItemRenderer, the ItemRenderer dispatches an event, waits for all the listeners to review it , and look at the event’s properties as the answer to the question.
It dispatches an event that bubbles (or is proxied up to the DataGrid or List) to some container acting as a list manager. It will set the event.isSelected property. Once the dispatchEvent() method returns, the ItemRenderer looks at that property.

 ...
    var theEvent : ThingieEvent = new ThingieEvent(IS_THINGIE_SELECTED, true);
    theEvent.thingie = data.thingie;

    this.dispatchEvent(theEvent); // ---- listeners execute here

    isThingieSelectedCheck.selected = theEvent.isSelected;
 ...

Note that after the .dispatchEvent(), the event has whatever value the listeners put in there. On the list manager side, the listener might look like this:

    private function onIsThingieSelected(event : ThingieEvent) : void
    {
        event.isSelected = (_thingieList.getIndexOf(event.thingie) != -1);
    }

Note that it does not cost anything to add a listener more than once, and using a weak reference prevents memory issues. The Ultimate Checkbox List Pattern uses bubbling events; if one is not fond of them, one can proxy the events through custom Column classes, then through the top-level Grid or Listbox, and then up to whatever is acting as the list manager.

An advantage to bubbling events is immunity to changes in the number of containers between the item renderer and the list manager. One can even encapsulate some set of containers into a component and embed it in another container without changing this pattern.

The Ultimate Checkbox List Pattern has several advantages over using a flag in the dataProvider item to persist checked status:

  • The dataProvider items can remain pure value object (e.g. unchanged from an loosly-linked data module)
  • The same item can have separate selection-states on an infinite number of lists
  • The list of selected items is always current and available at a high level; one does not need to iterate through the dataProvider items
  • Items remain selected even when they are not visible or if they are not in the dataProvider’s collection. One can page off and back and previously selected items are still selected.
  • Items can be selected and deselected across several different views (if the list manager tests membership using an ID instead  of object identity). E.g. one can have browse lists and search results that reflect each other’s selection (ee the next posting for details).

(Update: sample application in the final installment)

Go Ask Your Container

First in a series of five. This blog entry is part of my article in the Flash and Flex Magazine

One of the things I had to learn moving from Windows programming to Flash/ActionScript programming was all the asynchronous patterns (aka two-part procedures). If one needs to load a resource in the middle of a process, one cannot just call a loader and wait for the results before continuing. One has to register an event listener to the loader object and put the remainder of the process into that listener function. When the loader is done loading, it calls the listener, and the rest of the process goes on its merry way. While this is indeed asynchronous programming, events themselves are not asynchronous.

Events are dispatched (aka “fired”, “launched”, “broadcast”, “thrown”) from classes implementing IEventDispatcher – usually by descending from or containing the class EventDispatcher – by calling the event handler functions (“listeners”) previously registered. The dispatcher does not care how many listeners have registered themselves or what they do: it just calls every one registered for a particular message.

Event handlers are, at their core, callback functions. One can call them explicitly, but they are designed to be registered with a dispatcher, and wait for it to call them. One should keep these callback functions very lightweight because events themselves are not asynchronous.

When one to fires an event by calling a dispatcher’s dispatchEvent method, the method literates through the list of registered listener functions, calling each one with the Event object as a parameter, and waiting for it to return before calling the next listener function. Then the dispatchEvent method itself returns. The code that calls dispatchEvent can assume that, when that call returns, all the listeners have had a chance to see and modify the Event object.

One can use events as a bidirectional messages between the dispatcher and the listeners, not just a one-way notification system; the event object can receive information from the listeners as well as send information. Combined with bubbling events that allow containers to get events without registering with the originating dispatcher, this patterns allows nested objects like ItemRenderers to ask questions of their high-level containers without each intermediate container passing the events up and the results down. This relationship is a loosely-linked one: the dispatcher does not know what object is setting the answer properties of the Event object; the listener does not know what object is dispatching the Event object. The form can add or remove containers without breaking.

The Event class already has one Boolean property that is designed for listeners to set: the defaultPrevented property. Listeners can call event.preventDefault() to set this, and the dispatching code can check the value (the dispatchEvent method itself returns this value as well).

For example, an ItemRenderer needs to know if the data it is displaying is part of the set that the user wants to focus on. The data itself does not know, but the top-level form object does. The ItemRenderer can dispatch an event containing its data object and a property for the current status.

public class AmIInUserFocusEvent extends Event
{ 
    public function AmIInUserFocusEvent(type : String = AM_I_IN_FOCUS, bubbles : Boolean = true, cancelable : Boolean = false) 
    { 
        super(type, bubbles, cancelable);
    }

    public var rowData : RowData; public var isInUserFocus : Boolean; 
}

In the ItemRenderer:

 ...
       var newEvent : AmIInUserFocusEvent = new AmIInUserFocusEvent(AM_I_IN_FOCUS, true);
       newEvent.rowData = this.data as RowData;

       this.dispatchEvent(newEvent); // ---- listeners execute here 

       if (newEvent.isInUserFocus) 
           text.styleName = "focusStyle"; 
       else 
           text.styleName = "neglectedStyle"; 
 ...

In some container that holds the item renderer’s list or grid :

 ... 
        this.addEventListener(AM_I_IN_FOCUS, onFocusQuestion);

        ....

    private function onFocusQuestion(event : AmIInUserFocusEvent) : void
    {
        event.isInUserFocus = focusList.contains(event.rowData); 
    }
 ...

To summarize, in additional to sending notifications and data out, events can also get answers. ActionScript’s built-in event framework allows loosely-coupled communication between different parts of a form, even across component bounds.

(Update: sample application in the final installment)

Distributed Dates

When you announce an event in email or put in on your web site, instead of just showing text describing the event, make it easy for your audience to save the date. With the prevalence of on-line and PDA and cell phone calendars, you can get your event on their calendar easily.

Providing the event information yourself instead of depending on your audience to copy ensures accuracy (i.e. no transcription or transposition errors) and complete: you can include the street address, contact phone number and email, directions, links to on-line maps, prerequisites, and preparation suggestions (e.g. “Bring a jacket because it gets cold in the evening”)

I’ll be talking about three different ways to communicate event information:

  • Load it on their Yahoo or Google Calendar using a link
  • Distribute it as an iCalendarFile
  • Share your public calendar

Load It on Their Yahoo or Google Calendar Using a Link

Both Yahoo and Google have a format for describing a calendar event as a URL. If you supply these as links on your web page or HTML email, users can click them and immediately add the event to their own calendars.

Yahoo Calendar Links

The Yahoo Calendar link is at the bottom of each Yahoo Calendar page as text. Note that the link represents the event as it was when the page appeared; it does not dynamically reflect any changed you make, so save any changes and then copy the link.

Google Calendar Links

The details page for a Google Calendar event has a link in the lower right corner: “Publish this event”. It will pop-up a dialog with the address selected for easy copying.

Distribute It as an iCalendar File

As with most computer things, calendar items have a standard format so every system can understand the data. The iCalendar format replaces an older format named vCalendar. You can send this file as an email attachment or as a downloadable file on your web site (example below)

Almost all calendar applications (like Outlook/Exchange, Backpack, Notes, Sunbird) will import “iCal” files (some will export as well). Some operating systems associate the .ical and .ics file extensions with the calendar program so that program automatically imports the calendar file whenever the file is “executed”.

Share Your Calendar

Both Yahoo and Google allow you to create an on-line calendar and publish it so users of those systems can merge it (subscribe) with their own calendars. Your subscribers will see events as soon as you add them with no action on their part. They will also see them in relation to their own scheduled calendar events, so they can plan and anticipate.

Here is a Yahoo Calendar that subscribes to several other calendars. All the subscribed calendars show up as items in the right-hand column.

Subscribing to a Yahoo Calendar

Instruct your users to go to their Yahoo Calendar and select the “Edit” link My Time Lines in the upper right corner of the top date display (not the top right corner of the screen)

They can select any of their group’s calendar or a friend’s calendar:

Here is a Google Calendar that subscribes to another calendar. The events are color-coded to show which calendar they come from. In this case, pink is “my” events; red is for Sign Language Club De Anza calendar’s events.

Note that subscribing to someone else’s calendar does not expose your calendar

Sharing/Publishing Your Yahoo Calendar

Insure that the calendar you are going to share is completely public (do not share your personal calendar just because it has some public events on it). If you manage a Yahoo group, you can publish that group’s calendar. You can also create a separate Yahoo account to publish.

Pick a calendar and set its publication in the Calendar | Setting | Calendar page:

Subscribing to a Google Calendar

Tell your subscribers to choose the Other calendars | Add link on the left panel. They can select a friend’s calendar or enter the calendar’s address.

You can find the address of your calendar at Settings | Calendar Details (scroll down) Calendar Address

Sharing/Publishing Your Google Calendar

Google Calendar allows you to create many calendars and publish them individually.

Specify your calendar’s publication in the Calendar | Setting (top left corner)| Calendars | Share this calendar

You can make the calendar either public or available to specific Google Calendar users.


Example of a Yahoo Calendar URL – wrapped to multiple lines for ease of reading

http://calendar.yahoo.com/?
  v=60&
  VIEW=d&
  in_loc=Adobe+HQ+-+San+Jose&
  in_csz=San+Jose%2c+CA+95110&
  type=20&
  TITLE=Silvafug+South+-+San+Jose+-+Design+and+Development+Workflow&
  ST=20090515T013000Z&DUR=0100&
  URL=http%3a%2f%2fria.meetup.com%2f12%2fcalendar%2f10232257%2f&
  DESC=For+full+details%2c+including+the+address%2c+and+to+RSVP+see%3a%0ahttp%3a%2f
     %2fria.meetup.com%2f12%2fcalendar%2f10232257
    %2f%0aFlex+3+%26+Adobe+AIR+Junkies%0aThere+are+two+sessions+this+month+12th+in+San+Francisco+and+14th+in+San+Jose.+The+presentations+will...

Example of a Google Calendar URL – wrapped to multiple lines for ease of reading

http://www.google.com/calendar/event?
 action=TEMPLATE&
 text=Silvafug+South+-+San+Jose+-+Design+and+Development+Workflow&
 dates=20090515T013000Z%2f20090515T023000Z&location=San+Jose%2c+CA+95110&
 sprop=website%3ahttp%3a%2f%2fria.meetup.com%2f12%2fcalendar%2f10232257%2f&
 sprop=name%3aFlex+3+%26+Adobe+AIR+Junkies&
 details=For+full+details%2c+including+the+address%2c+and+to+RSVP+see%3a%0ahttp%3a%2f
  %2fria.meetup.com%2f12%2fcalendar%2f10232257
  %2f%0aFlex+3+%26+Adobe+AIR+Junkies%0aThere+are+two+sessions+this+month+12th+in+San+Francisco+and+14th+in+San+Jose.+The+presentations+will+be+the+same+so+RSVP+to+the+one+that+is+a%26hellip%3b%22

Example of an iCalendar file (from Wikipedia)
Here is a simple example of an iCalendar object, “Bastille Day Party” event which occurs July 14, 1997 17:00 (UTC) through July 15, 1997 03:59:59 (UTC):

BEGIN:VCALENDARVERSION:2.0PRODID:-//hacksw/handcal//NONSGML v1.0//ENBEGIN:VEVENTDTSTART:19970714T170000ZDTEND:19970715T035959ZSUMMARY:Bastille Day PartyEND:VEVENTEND:VCALENDAR

Other References

See also toomanydaves…words by davelms