Adobe Flex迷你教程 — DataGrid滚动条单击异常处理
我们对于DataGrid一般有这样的需求:
单击DataGrid的某一行,拿到这行的数据,进行下步动作(我们为此注册了一个click函数dtGrid_clickHandler(event))。
结果:有时我们数据比较多,DataGrid自动产生了滚动条。
我们本想按住滚动条滑动,可是不小心单击了它,同样也会触发dtGrid_clickHandler(event)函数。
这样我们里面写的 trace(dtGrid.selectedItem.value);就会出错。
原因分析:仔细研究后发现 原来滚动条是个Button,这个Button在DataGrid的上面,单击这个Button后,下面的DataGrid冒泡的也拿到了单击事件。
所以,加上 判断 if(event.target is Button) reutrn;
<?xml version="1.0"?>
<!--
* Created with IntelliJ IDEA.
* User: DongYang
* Date: 13-3-12
* Time: 上午12:07
* Progress every day a little more -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<s:DataGrid id="dtGrid" width="180" height="129" top="10" left="10"
dataProvider="{_data}" click="dtGrid_clickHandler(event)">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="name"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
<s:Button id="initData" x="366" y="57" label="添加数据" click="initData_clickHandler(event)"/>
<fx:Script><![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var _data:ArrayCollection;
private function dtGrid_clickHandler(event:MouseEvent):void {
if (event.target is Button || null == dtGrid.selectedItem) return;
trace(dtGrid.selectedItem.value);
}
private function initData_clickHandler(event:MouseEvent):void {
var array:ArrayCollection = new ArrayCollection();
for (var i:int = 1; i < 10; i++) {
array.addItem({name: "test" + i, value: i});
}
_data = array;
}
]]></fx:Script>
</s:Application>
<!--
* Created with IntelliJ IDEA.
* User: DongYang
* Date: 13-3-12
* Time: 上午12:07
* Progress every day a little more -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<s:DataGrid id="dtGrid" width="180" height="129" top="10" left="10"
dataProvider="{_data}" click="dtGrid_clickHandler(event)">
<s:columns>
<s:ArrayList>
<s:GridColumn dataField="name"/>
</s:ArrayList>
</s:columns>
</s:DataGrid>
<s:Button id="initData" x="366" y="57" label="添加数据" click="initData_clickHandler(event)"/>
<fx:Script><![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var _data:ArrayCollection;
private function dtGrid_clickHandler(event:MouseEvent):void {
if (event.target is Button || null == dtGrid.selectedItem) return;
trace(dtGrid.selectedItem.value);
}
private function initData_clickHandler(event:MouseEvent):void {
var array:ArrayCollection = new ArrayCollection();
for (var i:int = 1; i < 10; i++) {
array.addItem({name: "test" + i, value: i});
}
_data = array;
}
]]></fx:Script>
</s:Application>