我需要一种方法来等待运行parseCSV命令,直到readFile事件更新了importData的内容。我已经看过一些关于自定义事件调度程序的事情,但在我的情况下无法弄清楚如何使用它们。
private var importData : String;
public function importFile(event:MouseEvent):void {
var data:String = chooseFile();
parseCSV(importData);
}
public function chooseFile ():String {
var filetype:FileFilter = new FileFilter("CSV Files(*.csv)","*.csv");
var file:File = File.userDirectory;
file.browseForOpen("Select CSV file to import", [filetype]);
file.addEventListener(Event.SELECT, readFile);
return importData;
}
public function readFile (event:Event):void {
var filestream:FileStream = new FileStream();
filestream.open(event.target as File, FileMode.READ);
importData = filestream.readUTFBytes(filestream.bytesAvailable);
filestream.close();
}
答案 0 :(得分:2)
您需要添加一些回调或添加一些事件侦听器。我更喜欢回调:
function importFile(...) {
choseFile(function(file:File) {
readFile(file, parseCSV);
});
}
function choseFile(callback:Function) {
...
file.addEventListener(Event.SELECT, function(event:Event) {
callback(File(event.target));
});
}
function readFile(file:File, callback:Function) {
var data = ... read data from file ....;
callback(data);
}
答案 1 :(得分:2)
如何在readFile函数中添加该行?
public function readFile (event:Event):void {
var filestream:FileStream = new FileStream();
filestream.open(event.target as File, FileMode.READ);
importData = filestream.readUTFBytes(filestream.bytesAvailable);
parseCSV(importData);
filestream.close();
}
一旦设置了importData,就会执行该命令。
如果您希望使用自定义事件路线,则需要调度自己的自定义事件。每个Event都有一个type参数,它只是一个用来标识它的字符串。例如,Event.CHANGE与使用“change”相同。
static public const CUSTOM = "myCustomEvent";
public function someConstructor():void {
addEventListener(CUSTOM, onCustomEvent);
}
public function testDispatch():void{
dispatchEvent(new Event(CUSTOM));
}
private function onCustomEvent(e:Event):void{
trace("custom event Dispatched");
}
所以你可以尝试这样的事情。
public function importFile(event:MouseEvent):void {
addEventListener(CUSTOM, onImport);
var data:String = chooseFile();
}
private function onImport(e:Event):void {
parseCSV(importData);
}
public function readFile (event:Event):void {
var filestream:FileStream = new FileStream();
filestream.open(event.target as File, FileMode.READ);
importData = filestream.readUTFBytes(filestream.bytesAvailable);
dispatchEvent(new Event(CUSTOM));
filestream.close();
}