Search code examples
actionscript-3eventsaddeventlistenerdispatchevent

what to addEventListener to when listening for custom events?


I am sending an event when an sql query returns no matches so that I can continue with the addition to the database.. It seems like actionscript is requiring that I attach the listener to something, but I don't really have any variables that seem like logical candidates at the point where I am in my code.

I just want to listen for the isNewRecord event to be called so that I can then run the insert query; right now it's saying call to possibly undefined method for addEventListern and for dispatchEvent

public function addBG(BG:Number, datetime:String, batch:Boolean = false):void{
        checkRecord('Gb', datetime, matchRecord);

        addEventListener("isNewRecord", recordExists);

        function recordExists()
        {/*code to execute query*/}

public function matchRecord(result:SQLResult):void {
        var match:String = result.data[0];
        if (match == null) {
            var allClear:Event = new Event("isNewRecord");
            dispatchEvent(allClear);
        }
    }

Solution

  • Your code is buggy. You have a function within a function.

    Also, is your code extending EventDispatcher class (or any class that extends it, like Sprite, MovieClip, etc.?) Make sure it is.

    Try this:

    public function addBG(BG:Number, datetime:String, batch:Boolean = false):void
    {
            // note, you're adding this event listener EVERY TIME you call the 
            // addBG function, so make sure you remove it OR add it somewhere in the
            // init or complete functions
    
            addEventListener("isNewRecord", recordExists);
            checkRecord('Gb', datetime, matchRecord);    
    }
    public function recordExists():void
    {/*code to execute query*/}
    
    public function matchRecord(result:SQLResult):void {
            var match:String = result.data[0];
            if (match == null) {
                var allClear:Event = new Event("isNewRecord");
                dispatchEvent(allClear);
            }
    }