How to dispatch a custom event in Actionscript 3

This is going to be a very simple example of how to dispatch an event. In actionscript 3, you dispatch an event by extending the EventDispatcher class. I’m not going to get into a big complicated explanation right now, but I will show you a couple of simple examples.

One good thing about the Sprite class is that it already extends the EventDispatcher class, so if you are working from your document class, or your class extends Sprite/Movieclip, you can use this anywhere in your class:

// Declare at the top...
public static const CUSTOM_EVENT:String = "customEvent";
// ... Somewhere in your class...
dispatchEvent(new Event(CUSTOM_EVENT));

Let’s say for example you have the following class:

package{
   
    import flash.display.Sprite;
    import flash.events.EventDispatcher;
   
    public class Cat extends Sprite{
       
        public static const MEOW:String = "meow";
       
        public function Cat(){         
        }
       
        public function meow(){
           
            dispatchEvent(new Event(MEOW));
        }
    }
}

Now create an instance from your timeline:

var cat:Cat = new Cat

next:

cat.addEventListener(Cat.MEOW, doSomething);
cat.meow();

function doSomething(event:Event){
    trace("The cat is hungry!");
}

Ok, so this really doesn’t do anything useful, but you can see how you could use this idea to broadcast events from your objects. This is by no means comprehensive, but I have noticed that this simple concept has eluded a lot of people. Later I will write a more robust tutorial showing how to extend the EventDispatcher class and do some cool stuff.

Load AS2 SWF into your AS3 Project

There is a Flash game that I have been working on that I’ve had to load into an as3 interface and I noticed that my previous class will not work to do this.

There were a few modifications that I had to make… Here is the Actionscript 3 class:

// SWFLoader Class by Rick Nuthman
// 2.16.10
//
// Usage:
/*
var game:SWFLoaderAs2 = new SWFLoaderAs2("yourSwf.swf",20,0)
game.dispatcher.addEventListener("ready", gameLoaded);
function gameLoaded(event:Event){
   
    addChild(game);
}
*/


package com.frigidfish{

    import flash.display.Sprite;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.net.URLRequest;
    import flash.events.EventDispatcher;       

    public class SWFLoaderAs2 extends Sprite {     
       
        public var dispatcher:EventDispatcher   = new EventDispatcher();
        private var contentLoader:Loader;      
       
       
        public function SWFLoaderAs2(pathToTheContent,x,y) {
           
            this.x = x;
            this.y = y;
            loadSWF(pathToTheContent);
        }
           
        private function loadSWF(pathToTheContent):void {
           
            var request:URLRequest  = new URLRequest(pathToTheContent);
            contentLoader           = new Loader();
            contentLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,swfLoaded);
            contentLoader.load(request);
        }

        private function swfLoaded(e:Event):void {
           
            addChild(contentLoader);
            dispatcher.dispatchEvent(new Event("ready"));                  
        }
    }
}

usage:

var game:SWFLoaderAs2 = new SWFLoaderAs2("yourSwf.swf",20,0)
game.dispatcher.addEventListener("ready", gameLoaded);
function gameLoaded(event:Event){
   
    addChild(game);
}

This will certainly work to load an as2 swf into your as3 project,
but keep in mind that you will not be able to access methods and properties of your as2 swf.
I will be updating this class or adding another to make this possible. In the meantime,
Grant Skinner has created this to make the job a snap!

Load SWF via Actionscript 3 with this class

Here is a class that you can use to load swf’s into an object that you can display or do whatever you’d like with:

// SWFLoader Class by Rick Nuthman
// 2.10.10
//
// Usage:
/*
var mySWF:Object;
mySWF = SWFLoader.create("urlToSWF.swf", 0,0);
mySWF.dispatcher.addEventListener("ready", displaySwf);
function displaySwf(event:Event){
    addChild(mySWF.swf);
}
*/


package com.frigidfish{

    import flash.display.Sprite;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.net.URLRequest;
    import flash.events.EventDispatcher

    public class SWFLoader{        

        public function SWFLoader() {
        }

        public static function create(url, x=0,y=0):Object {
           
            var loaded:Event                = new Event("ready");
            var dispatcher:EventDispatcher  = new EventDispatcher();
            var swf:Sprite                  = new Sprite  ;
            var mLoader:Loader              = new Loader  ;
            var obj:Object                  = new Object;
           
            obj.swf = swf;
            obj.dispatcher = dispatcher;
           
            swf.x = x;
            swf.y = y;
           
            var mRequest:URLRequest = new URLRequest(url);
            mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,swfLoaded);

            mLoader.load(mRequest);

            function swfLoaded(event:Event) {
                var target = event.currentTarget.content;              
                swf.addChild(target);  
                dispatcher.dispatchEvent(loaded);
            }
           
            return obj;
        }
    }
}

You don’t need to make an instance of the class, just use the static function ‘create’ like so:

var mySWF:Object;
mySWF = SWFLoader.create("urlToSWF.swf", 0,0);
// You can replace 0,0 in the previous line with
// initial x,y coordinates for your swf
mySWF.dispatcher.addEventListener("ready", displaySwf);
function displaySwf(event:Event){
    addChild(mySWF.swf);
}

I have been using this class to load a bunch of swfs into an array of objects.. I built a preloader that says something like “loading foo.swf…” for each swf as they are loading. Then when the “ready” event has fired for all of the swfs I add them all to a container sprite and display them.

flash and php – Send/Receive Variables from Actionscript 3 & PHP

Below is a class that I made that can be used to send a group of variables to a php script on a server and receive the results. I use this all the time when working between flash and php in my projects!

// FlashPHP Class by Rick Nuthman
// 8.28.09
// Constructor receives 2 arguments:
// url:String - The url to the PHP file
// flashVars:Object - An object that contains variables to be sent to the url
//
// The class dispatches 1 event called "ready" once the php transaction is complete.
// listen for this event. Once it's received you can access returned variabled from receievedVars.

package com.frigidfish{

    import flash.net.URLVariables;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequestMethod;
    import flash.events.EventDispatcher;
    import flash.events.Event;

    public class FlashPHP extends EventDispatcher {
       
        // Public Properties
        public var receivedVars:URLVariables;      
       
        // Private Properties
        private var url:String;    
        private var flashVars:Object;
        private var request:URLRequest;
       
        private var completeEvent:Event              = new Event("ready");
        private var variables:URLVariables           = new URLVariables();
        private var loader:URLLoader                 = new URLLoader();

        public function FlashPHP(url:String, flashVars:Object) {
           
            this.flashVars                      = flashVars;
            this.url                            = url+"?r="+ new Date().getTime();
           
            parseVariables();
        }

        // Private Methods
        private function parseVariables() {
           
            for (var item in flashVars) {
               
                variables[item] = flashVars[item];             
            }
           
            sendVariables();
        }

        private function sendVariables() {
           
            request                                 = new URLRequest(url);
            request.method                          = URLRequestMethod.POST;
            request.data                            = variables;
           
            loader.dataFormat                       = URLLoaderDataFormat.VARIABLES;           
            loader.addEventListener(Event.COMPLETE, variablesAreLoaded);
            loader.load(request);
        }

        function variablesAreLoaded(event:Event) {
           
            receivedVars                            = new URLVariables(loader.data);
            dispatchEvent(completeEvent);          
        }
    }
}

Here is an example of how to implement it:

import com.frigidfish.FlashPHP;
var score:String = "100";
var playerName:String = "Bobby";
var phpData:*;

var playerObject:Object = new Object();
playerObject.score = score;
playerObject.playerName = playerName;

var flashPHP:FlashPHP = new FlashPHP("http://www.yoursite.com/yourphp.php", playerObject);
flashPHP.addEventListener("ready", processPHPVars);

function processPHPVars(event:Event){
// put the object that php sends back into a var (in this case phpData)

phpData = event.target.receivedVars;
trace(phpData.success);
}

Of course it will be necessary to know what to do with the data on the PHP side… here is a simple script that receives that variables and sends back a simple response var called ‘success’:

<?php
$teamName = $_POST['playerName'];
$score = $_POST['score'];
// Here you would put any processing functions...
//...

$success = "1";
//...
$returnVars = array();
$returnVars['success'] = $success;
$returnString = http_build_query($returnVars);
echo $returnString;
?>

Basically, this script does nothing with the variables that are collected, but as you can see, it just takes what is posted from flash and assigns it to php variables. Lastly, we create a new array to contain any vars that will be sent back to flash. This array is converted into a query string which is translated by FlashPHP into an object containing the variables by key names created in PHP.

I hope this makes sense, it’s actually quite easy to use! Don’t forget to wait for the FlashPHP “ready” event to trigger before attempting to access its receivedvars property. Feel free to ask any questions if anything doesn’t make sense šŸ™‚

Download Example

actionscript 3 preloader freezes at 100% (SOLVED!)

Have you ever embedded an swf into an html docuement and all seemed fine until you started getting calls from customers saying that the preloader is stuck at 100%?

Well I have, and it took me quite some time to figure this out.

If you embedĀ  different wmode, such as wmode=transparent,Ā  Firefox will load the first frame of your swf but then it appears to lock up!

It turns out that theĀ  loaderInfo Event.COMPLETE and PROGRESS are not firing.

Here is my working preloader:

stop();

var preLoaderPercent:Number = 0;

addEventListener(Event.ENTER_FRAME, loadComplete);

function loadComplete(e:Event):void {

if (this.loaderInfo.bytesLoaded == this.loaderInfo.bytesTotal) {

removeEventListener(Event.ENTER_FRAME, loadComplete);
this.loaderInfo.removeEventListener(Event.COMPLETE, loadComplete);
this.loaderInfo.removeEventListener(ProgressEvent.PROGRESS, loadProgress);
gotoAndStop(2);
}
}

this.loaderInfo.addEventListener(Event.COMPLETE, loadComplete);
this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);

function loadProgress(e:ProgressEvent):void {
preLoaderPercent = e.bytesLoaded / e.bytesTotal;
preloader.percentText.text = Math.ceil(preLoaderPercent * 100) + "%";
}

Basically this is a normal preloader with one addition.. On each frame (line 5) the function loadComplete is called. This function is SUPPOSED to be called when ProgressEvent.PROGRESS (line 19) is fired. Anyway, loadComplete (line 7) checks to see if the number of bytes loaded is the actual size of the file. This is basically a failsafe in the case that ProgressEvent.PROGRESSĀ  fails to fire!

What a weird bug.. Anyway, it works!