在 Flex DataGrid 的第一行中,itemRenderer 将初始化两次。跟踪结果显示 flex 框架可能正在创建第一行的 itemRenderer 的两个实例。在一个更复杂的应用程序中,itemRenderer 包含一个数据绑定的 ColorPicker,我们看到由于这个问题而发生了无限循环。只有第一行的 itemRenderer 被初始化了两次。有没有办法覆盖 flex 的行为并阻止这种情况发生?下面的代码演示了这个问题:
主要应用:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="on_initialize(event);">
<mx:Script>
<![CDATA[
/**
* This experiment shows how the first row's itemrenderer is instantiated/added/initialized twice.
* We've never even noticed this before we found that a data-bound ColorPicker enters a infinite
* loop when it is within an itemRenderer.
*/
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
private var dg_array:Array;
private var dg_arrayCollection:ArrayCollection;
private function on_initialize(event:FlexEvent):void {
dg_array = new Array();
dg_arrayCollection = new ArrayCollection();
dg_arrayCollection.addItem("item 1");
dg_arrayCollection.addItem("item 2");
dg.dataProvider = dg_arrayCollection;
}
]]>
</mx:Script>
<mx:DataGrid id="dg" width="100%" height="100%" rowCount="5">
<mx:columns>
<mx:DataGridColumn headerText="Name" itemRenderer="SimpleItemRenderer"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
简单项目渲染器:
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300" initialize="//on_initialize(event);">
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
[Bindable]
override public function set data(value:Object):void { _data = value; }
override public function get data():Object { return _data; }
private var _data:Object;
private function on_initialize_textInput(event:FlexEvent):void {
trace("initialize:event.target="+event.target+", " + _data); // runs twice, for the first item only
}
private function on_creationComplete_textInput(event:FlexEvent):void {
trace("creationComplete:event.target="+event.target+", " + _data); // runs twice, for the first item only
}
]]>
</mx:Script>
<mx:TextInput text="{data}" id="textInput" initialize="on_initialize_textInput(event);" creationComplete="on_creationComplete_textInput(event);"/>
</mx:Canvas>
缩写输出:
初始化:event.target=ItemRenderers0.dg...SimpleItemRenderer12.textInput,null 初始化:event.target=ItemRenderers0.dg...SimpleItemRenderer24.textInput,null 创建完成:event.target=ItemRenderers0.dg...SimpleItemRenderer24.textInput,项目 1 初始化:event.target=ItemRenderers0.dg...SimpleItemRenderer29.textInput,null creationComplete:event.target=ItemRenderers0.dg...SimpleItemRenderer29.textInput,项目 2 creationComplete:event.target=ItemRenderers0.dg...SimpleItemRenderer12 .textInput,第 1 项