2

I have one as3 file which handles other files (small games). All files are AS3 except for one which is AS2 and it is too big for me to rewrite it into AS3. In AS3 i use:

dispatchEvent(new Event("ending", true));

when game is finished. I need to dispatch "ending" in AS2 file, so my AS3 main file can do it's magic. Could someone translate this line from as3 to as2?

Kosinek
  • 21
  • 1
  • http://stackoverflow.com/questions/877871/can-an-as2-swf-be-loaded-into-an-as3-swf-how-can-i-add-this-to-the-stage-and-in – Pier Sep 01 '13 at 21:06

1 Answers1

1

The event model is just a bunch of callbacks associated with event types (strings). The EventDispatcher maintains this association and iterates over the callbacks when a specific event is triggered by it.

This is pretty trivial to recreate yourself, and in you case you can simplify it greatly.

Here's an example of what could be a simple EventDispatcher in AS2:

function EventDispatcher():Object
{
    var listeners:Object = { };

    return {

        addEventListener: function(type:String, callback:Function)
        {
            listeners[type] = callback;
        },

        dispatchEvent: function(type:String)
        {
            for(var i:String in listeners)
            {
                if(i === type) listeners[i]();
            }
        }

    };
}

And its implementation:

// Create the event dispatcher.
var eventDispatcher:Object = EventDispatcher();

// Add an event listener as with AS3.
eventDispatcher.addEventListener("ending", endGame);

// Define the handler function.
function endGame():Void
{
    trace("Game has ended.");
}

// Dispatch an event.
eventDispatcher.dispatchEvent("ending");

If you want to bring it closer to the AS3 Event model, you need to create an 'Event' object within the dispatchEvent loop and pass that to the handler, something like this:

dispatchEvent: function(type)
{
    for(var i:String in listeners)
    {
        var event:Object = { type: i, target: this };
        if(i === type) listeners[i](event);
    }
}
Marty
  • 39,033
  • 19
  • 93
  • 162