Friday, October 17, 2008

ActionScript scoping weirdness

Today I got the following error when I ran my Flex app:


TypeError: Error #1010: A term is undefined and has no properties.


Some quick searching on the web didn't reveal much except that it might have to do with a DisplayObject having visible == false. Great, except the object in question isn't a DisplayObject.

I looked into the code and saw this:

private function foo() : void
{
myObject.myProp = "Hello World";

var myObj : MyClass = new MyClass();

// stuff
}

The problem is that I was accidentally using myObject before actually creating it. In any other language, this would generate a compile error, but ActionScript, in its infinite wisdom, scopes the variable to the entire function, not just to the code following the declaration.

The solution: Move the offending line to after the declaration.

Thursday, October 16, 2008

Forcing screen updates in Flex/ActionScript 3

I'm working on a Flex app that has full undo functionality. After an undo or redo, sometime the display is out of sync with the underlying data. That's because various things don't refresh themselves properly even with data binding.

For example, if you have a DataGrid backed by an ArrayCollection, changes to the collection will reflect properly in the display because the DataGrid is listening for collection events. But if you changed one property of an object in the collection, DataGrid may not pick that up (see http://www.barneyb.com/barneyblog/2007/06/23/another-flex-weirdnessgotcha/)

I experimented with the ideas presented in that article and found that calling executeBindings(true) on my app's root object after an undo works beautifully:

public function postUndo() : void
{
Application.application.executeBindings(true);
}

Upon further reflection and experimentation, it looks like the reason DataGrid might not see property changes has to do with a subtlety in data binding. If your DataGridColumn's dataField is marked as [Bindable], then changes should come through OK. For example, you might have this:

public class MyObject
{
private var m_foo : String;

[Bindable]
public function get Foo() : String
{
return m_foo;
}

public function set Foo(foo : String) : void
{
m_foo = foo;
}
}

...

<mx:datagrid dataprovider="some ArrayCollection of MyObject">
<mx:datagridcolumn datafield="Foo">
</mx:datagridcolumn>
</mx:datagrid>

In this case, any time you set someMyObject.Foo, the grid will update.

But because data binding wraps the setter in a proxy to cause events to fire, if you set m_foo directly, the data binding events never fire, and the grid datagrid doesn't update. That's when you'd need to call executeBindings().