1

我需要一种方法来等待运行 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();
    }
4

2 回答 2

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);
}
于 2011-02-27T04:47:56.403 回答
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.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();
}
于 2011-02-27T13:33:03.687 回答