Channel Directions in ActionScript

ActionScript doesn’t have built-in support for channels or concurrency like Go does. However, we can simulate a similar behavior using events and event dispatchers. Here’s an equivalent implementation:

package {
    import flash.events.EventDispatcher;
    import flash.events.Event;

    public class ChannelDirections extends EventDispatcher {
        private var pings:EventDispatcher;
        private var pongs:EventDispatcher;

        public function ChannelDirections() {
            pings = new EventDispatcher();
            pongs = new EventDispatcher();

            ping(pings, "passed message");
            pong(pings, pongs);

            pongs.addEventListener("message", onPongMessage);
        }

        private function ping(pings:EventDispatcher, msg:String):void {
            pings.dispatchEvent(new Event(msg));
        }

        private function pong(pings:EventDispatcher, pongs:EventDispatcher):void {
            pings.addEventListener("passed message", function(e:Event):void {
                pongs.dispatchEvent(new Event(e.type));
            });
        }

        private function onPongMessage(e:Event):void {
            trace(e.type);
        }
    }
}

In this ActionScript implementation, we use EventDispatcher objects to simulate channels. The ping function dispatches an event, while the pong function listens for that event and then dispatches a new event on the pongs dispatcher.

The ping function only sends values (dispatches events). It would be a compile-time error to try to add an event listener in this function.

private function ping(pings:EventDispatcher, msg:String):void {
    pings.dispatchEvent(new Event(msg));
}

The pong function accepts two event dispatchers: one for receiving (pings) and another for sending (pongs).

private function pong(pings:EventDispatcher, pongs:EventDispatcher):void {
    pings.addEventListener("passed message", function(e:Event):void {
        pongs.dispatchEvent(new Event(e.type));
    });
}

In the main function (which is the constructor in this case), we create the event dispatchers, call the functions, and set up the final event listener to print the result.

public function ChannelDirections() {
    pings = new EventDispatcher();
    pongs = new EventDispatcher();

    ping(pings, "passed message");
    pong(pings, pongs);

    pongs.addEventListener("message", onPongMessage);
}

To run this ActionScript code, you would typically compile it into a SWF file and then run it in a Flash Player or AIR runtime environment. The output would be:

passed message

This implementation demonstrates how to achieve a similar behavior to channel directions in ActionScript, using the language’s event system. While it’s not a direct translation, it captures the essence of the original example in a way that’s idiomatic to ActionScript.