2007年5月24日星期四

ActionScript3 Tip Of the Day Update!(Version 20070518)


以前就介绍过ActionScript3 Tip Of the Day,只要过了英语四级就不会有难度,这次的更新不仅是内容上的扩张和补充,最重要的是,作者已经为我们清楚得分好了章节,所以有些内容也是有重复的。









Announce: senocular has the real copyWrite!

通过DataField来正确处理DataGrid的ColumnIndex的变化

由于客户需求的不确定,我们常常会修改DataGrid里面的内容,时而多一列时而少一列,因此它引发了DataGrid的ColumnIndex的变化。
当我们在AcitonScript代码中对columnIndex进行判断时,常常会忘记改变columnIndex从而引发bug。

sample.mxml

<mx:DataGrid id="PersonInfoDG" dataProvider="{PersonInfo_ARRAY}">
<mx:columns>
<mx:Array>
<mx:DataGridColumn headerText="First Name" dataField="firstName"/>
<mx:DataGridColumn headerText="Last Name" dataField="lastName"/>
</mx:Array>
</mx:columns>
</mx:DataGrid>


sample.as

[Bindable]
private var PersonInfo_ARRAY:Array =
[{firstName:"aaa", lastName:"bbb"},
{firstName:"ccc", lastName:"ddd"}];

private function initListener():void {
PersonInfoDG.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, doDoubleClick);
}

private function doDoubleClick(event:ListEvent):void {
if (event.rowIndex > 0) {
if(event.columnIndex == 1) {
Alert.show("It's Last Name Column!")
}
}
}


增加了Address字段

sample.mxml

<mx:DataGrid creationComplete="initListener()" id="PersonInfoDG" dataProvider="{PersonInfo_ARRAY}"
doubleClickEnabled="true">
<mx:columns>
<mx:Array>
<mx:DataGridColumn headerText="First Name" dataField="firstName"/>
<mx:DataGridColumn headerText="Address" dataField="address"/>
<mx:DataGridColumn headerText="Last Name" dataField="lastName"/>
</mx:Array>
</mx:columns>
</mx:DataGrid>


sample.as

[Bindable]
private var PersonInfo_ARRAY:Array =
[{firstName:"aaa", lastName:"bbb", address:"AB Road"},
{firstName:"ccc", lastName:"ddd", address:"CD Road"}];
private function initListener():void {
PersonInfoDG.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, doDoubleClick);
}

private function doDoubleClick(event:ListEvent):void {
if (event.rowIndex > 0) {
if(event.columnIndex == 1) {
Alert.show("It's Last Name Column!")//It's Wrong! It has change to 2
}
}
}

那我们怎么样才能今可能得减少这种错误呢?我们发现,在columnIndex在跟着不断变化的同时,我们所要表示的内容一般是不变的。是的,我们可以通过字段dataField来进行判断,而且不会有影响。


private function doDoubleClick(event:ListEvent):void {
if (event.rowIndex > 0) {
for(var i:Number; i < PersonInfoDG.columns.length; i++) {
if(PersonInfoDG.columns[i].dataField == "lastName" && i == event.rowIndex) {
Alert.show("It's Last Name Column!")//It's Right! :)
Break;
}
}
}
}