Когда я запускаю этот код, если я нажимаю кнопку «testExportToCSV», приложение выполняется, как ожидается [открывается окно «Сохранить файл ...»]. Однако, как только я нажимаю эту кнопку, две другие кнопки затем каким-то образом запускают одно и то же окно ['save file to ...'], чтобы открыть, как если бы я нажал кнопку «testExportToCSV». Отлаживая приложение, я узнал, что две другие кнопки действительно входят в правильный метод обработки кликов, хотя каким-то образом заканчивается выполнение функции writeCSV (event: MouseEvent), которая объявляется внутри функции WriteToOut(), которая только вызывается при нажатии кнопки «testExportToCSV».Adobe Flex Project: кнопки, кажется, вызывают неправильные методы
Пожалуйста, объясните, почему это происходит
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication 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="601"
backgroundColor="#3b5998"
creationComplete="windowedapplication1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.rpc.http.HTTPService;
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{}
/** ######## Click Handlers ######## */
protected function csvButton_clickHandler(event:MouseEvent):void{
trace("...inside csvButton_clickHandler(event:MouseEvent) ");
textBox.text = "In Export to csv method";
writeToOut();
}
protected function queryServer_clickHandler(event:MouseEvent):void{
trace("...inside queryServer_clickHandler(event:MouseEvent) ");
textBox.text = "In query server method";
serviceRequest.url = "https://msppluto.com/Planholders_Flex.php?customerId=15";
serviceRequest.send();
}
protected function refresh_clickHandler(event:MouseEvent):void{
trace("...inside refresh_clickHandler(event:MouseEvent) ");
textBox.text = "In refresh method";
validateNow();
}
/** ######## Write to ... ######## */
protected function writeToOut():void{
var myArray:Array = [];
for(var i:int = 0; i < 100; i++)
myArray[i] = {a:Math.random()*100, b:Math.random()*100, c:Math.random()};
var csv:String = '';
for(i = 0; i < 100; i++)
csv += myArray[i].a + ',' + myArray[i].b + ',' + myArray[i].c + '/n';
stage.doubleClickEnabled = true;
stage.addEventListener(MouseEvent.CLICK, writeCSV);
// why is this method being called when I click a different
// button ?????????????????????????????????????????
function writeCSV(event:MouseEvent):void{
var file:FileReference = new FileReference();
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(csv);
file.save(bytes, 'test.csv');
}
} // end writeToOut
]]>
</fx:Script>
<fx:Declarations>
<s:HTTPService
id="serviceRequest"
url="https://msppluto.com/Planholders_Flex.php"
useProxy="false">
</s:HTTPService>
</fx:Declarations>
<s:Label id="headline" text="HTTP Service" fontSize="45" x="10" y="10" color="#FFFFFF"></s:Label>
<s:Button id="testExportToCSV" x="14" y="187" minWidth="110" label="Export to csv" click="csvButton_clickHandler(event)"/>
<s:Button id="queryServerButton" x="14" y="216" minWidth="110" label="Query Server" click="queryServer_clickHandler(event)"/>
<s:Button id="refreshScreen" x="14" y="245" minWidth="110" label="refresh" click="refresh_clickHandler(event)"/>
<s:TextInput id="textBox" x="197" y="216" widthInChars="25" />
<mx:DataGrid id="dataGridForServiceRequest" x="575" y="160"
dataProvider="{serviceRequest.lastResult.planHolders.planHolder}">
<mx:columns>
<mx:DataGridColumn headerText="User ID" dataField="userid"/>
<mx:DataGridColumn headerText="User Name" dataField="username"/>
</mx:columns>
</mx:DataGrid>
Спасибо вам много! Это решило мою проблему. Если это не так уж сложно, не могли бы вы объяснить, что происходит (почему эта функция неожиданно вызвала?). –
Когда вы вызываете 'stage.addEventListener (MouseEvent.CLICK, writeCSV);', любой щелчок * на всем этапе * запускает 'writeCSV'. Так как ваши другие кнопки находятся на сцене, событие click вызывает оба прослушивателя. – Brian
@Brian Спасибо –