« Adobe AIR Linux Alpha | Main | Flex 4 »

Debugging Bindings with BindingManager

At last night's BFUG meeting Peter Farland demonstrated an undocumented class called BindingManager that is handy for debugging bindings in Flex. This class exists in both Flex 2 and Flex 3. Below is a quick example of how it is used:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" preinitialize="handlePreInitialize();">
<mx:Script>
<![CDATA[
private var _counter:int = 0;

private function changeText():void
{
    text1.text = "Changed Text " + _counter++;
}

private function handlePreInitialize():void
{
    BindingManager.debugBinding("text2.text");
}
]]>
</mx:Script>
<mx:Text id="text1" text="Initial Text"/>
<mx:Text id="text2" text="{text1.text}"/>
<mx:Button label="Update Text 1" click="changeText();"/>
</mx:Application>

The magic is the call to BindingManager.debugBinding(). The argument is the destination of the binding. The translation syntax is a little clearer if you aren't using an inline binding. For example the text2 binding above could also be written like this:

<mx:Text id="text2"/>
<mx:Binding source="text1.text" destination="text2.text"/>

Using either syntax, when the program is run I get the following output:

Binding: destString = text2.text, srcFunc result = Initial Text
Binding: destString = text2.text, error = TypeError: Error #1009: Cannot access a property or method of a null object reference.
Binding: destString = text2.text, srcFunc result = Initial Text
Binding: destString = text2.text, srcFunc result = Changed Text 0
Binding: destString = text2.text, srcFunc result = Changed Text 1
Binding: destString = text2.text, srcFunc result = Changed Text 2

The most interesting part of this output is the "TypeError" message. Normally errors like this are hidden from you on purpose by the binding mechanism. Now instead of having to set breakpoints in the framework it's possible to easily see just what is going on when a binding fires.

Tags: bindings flex