Flex object creation double the number of instances
I have the following spark application:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955"
minHeight="600" xmlns:local="*">
<local:TestComponent objects="{[new TestObject()]}">
</local:TestComponent>
</s:Application>
TestComponent:
package
{
import mx.core.UIComponent;
public class TestComponent extends UIComponent
{
public function TestComponent()
{}
public function set objects(array:Array):void
{}
}
}
TestObject:
package
{
public class TestObject
{
public function TestObject()
{}
public function set objs(value:Array): void
{}
}
}
I observed that the constructor of TestObject is called 2 times, and that two instance of TestObject are created.
Creation sequence goes like this:
- TestObject constructor
- TestComponent constructor
- TestObject constructor
- TestComponent.objects is called (value of the parameter contains only one object).
If I instantiate TestObject using the "ele开发者_开发知识库ment" way in mxml:
<local:TestComponent>
<local:objects>
<local:TestObject>
</local:TestObject>
</local:objects>
</local:TestComponent>
Only one instance of TestObject is created.
Anybody can explain why two objects are created when using the attribute syntax as oppose to the element syntax (which I thought was the same)?
The two syntaxes are definitely not the same. The main difference is that the first syntax will cause Flex to implement binding, whereas the second one does not.
The Flex compiler takes whatever you place in the squiggly brackets and puts it literally in an anonymous function that the binding calls whenever it executes. The specific reason why the constructor got called twice is because the binding is executed twice on UIComponent elements located in the Application's display list as the app starts up. The first execution happens in the Application's constructor, where all the bindings are initially created (prior to preinitialize
event). The second execution of the binding happens when the UIComponent is created. (Note: The number of binding executions that can occur before applicationComplete
event will vary for different components, as well as what your binding to them.)
If you want to use the binding, but not create garbage in the Application initialization, I'd recommend something like:
<fx:Declarations>
<local:TestObject id="testObject"/>
</fx:Declations>
<local:TestComponent objects="{[testObject]}"/>
精彩评论