views:

956

answers:

1

Hello!

In flex 3 I have a hierarchical data structure. I would like to display the content of it in a tree. My problem is that I have nodes which data calculated from children nodes. How to structure the hierarchy to make automatic changes to those parent nodes, if their children's data changed? For example:

  • Every node has a warning flag. If some of the children warning flag changed to true, then the parent warning flag should change automatically set to true.
  • A node integer field is the sum of the children integer fields, and if any of the children changes, the parent integer field "calculates" the sum immediately.

Is there an easy solution wit good structuring changes happen automatically, or I have to make some custom functions?

Thanks!

A: 

We do this by following this pattern:

  1. Create the method for calculating the value on the parent class, and make it bindable with an event.
  2. In the parent, add an event listener for when the child collection changes. To do this, the child collection should be an ArrayCollection or similar.
  3. When intercepting the change event, raise (or conditionally raise) the event attached to the Bindable metadata for the method mentioned in step 1.

This should cause any UI that's watching the aggregate property of the parent to be updated whenever a child is updated.

Here's an example:

public class Parent
{
    private var children:ArrayCollection = new ArrayCollection();

    public function Parent()
    {
        children.addEventListener(
            CollectionEvent.COLLECTION_CHANGE, 
            function(evt:CollectionEvent):void
            {
                if (...)
                {
                    dispatchEvent(new Event("warningStateChanged"));
                }
            }
        );
    }

    [Bindable("warningStateChanged")]
    public function containsWarnings():Boolean
    {
        for each (var child:Child in children)
        {
            if (child.hasWarning)
            {
                return true;
            }
        }
        return false;
    }
}
Jacob
really thanks.I also come to the solution creating a custom node type with listener on children's collection change event is needed.