Search code examples
actionscript-3flash-cs5urlloadertlf

ActionScript 3: How to remove EventListener with anon functions


I have written code as follows.
Problem is that I can't remove Event.COMPLETE event listener and when I call the loadData function twice or more, it works 2 times or more. Sorry for my bad english and worse explanation but I need to fix it today and I don't know what to do.
I think the code is pretty obvious. please help!

var ldr:URLLoader = new URLLoader();

function loadData(text_place, scrollbar, fileURL:String):void {
    text_place.wordWrap = true;
    var f:TextFormat = new TextFormat();
    f.align = TextFormatAlign.RIGHT;
    text_place.setTextFormat(f);
    ldr.dataFormat = URLLoaderDataFormat.TEXT;
    ldr.load(new URLRequest(fileURL));
    ldr.addEventListener(Event.COMPLETE, function ldr_complete(evt:Event){ 
        initText(text_place, ldr.data, scrollbar);
    });
    ldr.addEventListener(IOErrorEvent.IO_ERROR, loadError);
}

function initText(text_place:TLFTextField, fileContent, scrollbar):void {
    ldr.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
    text_place.htmlText = "";
    text_place.tlfMarkup = fileContent;
    scrollbar.update();
    trace("Data loaded");
}

function loadError(e:IOErrorEvent):void {
    trace("Error loading an external file.");
}

Solution

  • if you want to stop listening for an event after it triggered, you can unregister the anonymous listener in itself:

    ldr.addEventListener(Event.COMPLETE, function(event:Event):void
    {
         event.target.removeEventListener(event.type, arguments.callee);
         // ... do whatever you need to do here
    });
    

    But if you also want to stop listening for other events from the same dispatcher when it completes, such as your IOErrorEvent.IO_ERROR listener, you'd still need a reference to that listener to remove it.