Search code examples
actionscript-3event-handlingwaitcustom-events

How to run function only when parameter variable has been assigned?


I need a way to wait running the parseCSV command until the readFile event has updated the content of importData. I have seen a few things about custom event dispatchers but cannot quite figure out how to use them in my situation.

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();
    }

Solution

  • You'll either need to add some callbacks or add some event listeners. I prefer callbacks:

    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);
    }