Stroep

Just a collection of random works – Mark Knol

Archive for 'Code snippets'

JSFL dialog (2)

December 1st, 2011, under Code snippets, JSFL.

JSFL DialogWhile playing with JSFL and trying to create a faster interface for my name it right.jsfl I stumbled across a very interesting function inside JSFL. There is a powerful function called fl.getDocumentDOM().xmlPanel which shows dialogs using .xml-files. Actually you could use XUL (XML User Interface Language), which kinda looks like a mix of HTML and Flex. If you need a GUI for your JSFL script, you can open a nice custom dialog using XUL.

Why create tools inside a tool?

Yes, the Flash is a very nice IDE. But with JSFL you can extend it. You can build your own snippets and tools. It could be very helpful to automate some boring things. I think it is very powerful to have the ability to extend your environment for your everyday tasks.

Show a dialog with JSFL

Create a dialog file
This is an example of XUL. Save it as test-dialog.xml in your local commands folder.

<dialog title="JSFL dialog" buttons="accept, cancel">
  <vbox>
    <label control="myTextfield" value="Enter some text"/>  
    <textbox id="myTextfield"/>
    <label control="myColor" value="Choose a nice color"/>  
    <radiogroup id="myColor">  
      <radio label="Orange"/>  
      <radio selected="true" label="Violet"/>  
      <radio label="Yellow"/>  
    </radiogroup>  
  </vbox>
</dialog>
 

Open the dialog with JSFL
Save it as test-dialog.jsfl in the same folder as the .xml file.

// xmlPanel returns an Object with values of the dialog.
var xmlPanelOutput = fl.getDocumentDOM().xmlPanel(fl.configURI + "/Commands/test-dialog.xml");

if (xmlPanelOutput.dismiss == "accept") // user confirms dialog
{
  fl.trace("myTextfield: " + xmlPanelOutput.myTextfield);
  fl.trace("myColor: " + xmlPanelOutput.myColor);
}
else // user canceled dialog
{
 
}
 

Run it by clicking ‘Commands’ > ‘test-dialog’ in Flash; our custom dialog will show up. Nice! :D

Give me more; I want dynamic dialogs

If you check out the documentation of fl.getDocumentDOM().xmlPanel, you see you only can pass a uri to a xml file, but there is no way to pass a XML or Object to it. Adobe if you read this post; that would be nice. But I found a hack to create a dialog from JSFL by dynamically create a XML and save it as temporary file and open that one as xmlDialog. The file will be removed after showing the dialog.

function showXMLPanel(xmlString)
{
  var tempUrl = fl.configURI + "/Commands/temp-dialog-" + parseInt(777 * 777) + ".xml"
  FLfile.write(tempUrl, xmlString);
  var xmlPanelOutput = fl.getDocumentDOM().xmlPanel(tempUrl);
  FLfile.remove(tempUrl);
  return xmlPanelOutput;
}

This function displays a dialog from a (xml) string and returns the values like you would expect from the xmlPanel-function. You could use a XML object for this too, but I think it’s easier to hack some variables into it or make templates with strings.

// create an XUL with JSFL
var dialogXML = ”;
dialogXML += ‘<dialog title="JSFL dynamic dialog" buttons="accept, cancel">’;
dialogXML +=   ‘<hbox>’;
dialogXML +=     ‘<label value="Enter 2x something"/>’;
dialogXML +=     ‘<textbox id="myText1" value=""/>’;
dialogXML +=     ‘<textbox id="myText2" value=""/>’;
dialogXML +=   ‘</hbox>’;
dialogXML += ‘</dialog>’;

var xmlPanelOutput = showXMLPanel(dialogXML);
if (xmlPanelOutput.dismiss == "accept") // user confirms dialog
{
  fl.trace("myText1: " + xmlPanelOutput.myText1);
  fl.trace("myText2: " + xmlPanelOutput.myText2);
}
else // user canceled dialog
{
 
}
 

Since you are dealing with strings, you can manipulate and add extra elements. This allows you to pass data from JSFL to your dialog.

So, can you make panels too?

I really hate custom panels, because I never get my workspace right for two screens (moving/closing/opening panels the whole day), so there is no room for other panels. I start loving JSFL-scripts because you can assign a shortcut-key to it, which runs the tool, without having a panel in my workspace.

Conclusion

I like to create handy snippets and will share more in the future. But if you thought (just like me) this is some kind of a new feature: It’s not. :) Let me know if you have some nice references or JSFL scripts to share.

Learn more:

Tagged with , , .

Recently I found an interesting question on FlashFocus.nl, about creating light and shadows in a 2D environment. I started experimenting with this to see how far I could take it. I love to share the results and some insides about this fun project.

How to get started

The initial code that the topic starter used a loop through all objects, and used hitTestPoint-function to detect if the light hits a wall. Therefore he used a loop with 360 steps, used for all directions. In the innerloop it tries if it hits the wall, otherwise goes away from the light (using the direction of the outerloop), tries if it hits the wall. That loop goes on till it does hit a wall. It is a bit of trial and error, but I think it is very clever. At the end of each loop a lineTo is used to draw the light, so in the end it will be a shape with 360 vector points.

Speed of light

Now, that screams for optimization and speed. It’s a fun project to mix some things you have seen and want to try out for a long time. The first thing that I tried to make it faster, draw all objects into an BitmapData, and use the getPixel function instead of hitTestPoint, which is notable faster if you don’t move objects. I used that BitmapData object only too check if the light hits the objects; no one actually sees it. To use hitTestPoint, you must loop through all objects and detect if they hit. With a lot of objects, it would be slower. With BitmapData, you don’t need that loop, and you are free to use unlimited objects with even custom shapes. Less looping == faster, unlimited objects == awesome :)

More realism

I also wanted to make it look more realistic. Having light only is not close enough to realism. It needs shadows. I created an inverted shape of the light-shape and filled it with black (a). This creates a nice shadow, however has very hard bounds, which is ugly. So then I took the shape again and drawed with a nice transparent to black gradient (b). Those 2 layers have the BlendMode ALPHA. The holder of those has a solid shape fill (as big as the stage) with BlendMode LAYER. This creates a nice ‘hole’ which I think works very well as shadow if you make it half-transparent. Oh, the colored light-layer (c) is a gradient too, with the same shape as b, only with BlendMode ADD.

Re-using shape data

Another optimization I used was to use graphics data API. In this case I have 1 shape which could be reused 3 times. So before even drawing, I collect all points and commands in an Vector. When I have all data collected, it draws the light-layer and shadow-layer at first, then it pushes some extra points to the Array to make the outer shadow-layer. So with 1 Array of (manipulated) data I could draw multiple shapes. That’s a good case of using the graphics data, I guess.

Optimized trig functions

I also used the TrigLUT-class (Trigonometry LookUp Table) from jacksondunstan.com, since the loop heavily uses Math.sin and Math.cos. I could use the valNormalizedPositive() function from that class in this case. It’s very fast and for me it was fun to use that class. :D

But it is still too slow..

The most intense about this thing isn’t the calculation, but the rendering itself. The whole ‘canvas’ needs to be updated and redrawed every frame with lots of layers and blendmodes, which is very intense for the CPU. I don’t know if this would be possible with Stage3D, but that would be the last step to render really fast. And when that is possible, I’ll guess I could move the object real-time too, which makes it very interesting for games.

Check out the experiment:
» Lights and shadows

Let me know what you think about it and how does it perform on your computer?

Tagged with , , , .

While working on a game, I created a function spawner. The idea was to make a function which would call a function like createEnemy() a hundred times with an interval. So I quickly created a static function. Yes, I could use Chain, but this function was created in a minute and I haven’t thought of that class.

public static function create(total:int, interval:int, func:Function, delay:int = 0):void
{
    for (var i:int; i < total; ++i)
    {
        setTimeout(func, delay + interval * i);
    }
}
 

This function is easy to understand. Maybe it’s not needed as a new class, but it could be handy in a game. By the way; I use setTimeout a lot, it’s sometimes easier than the Timer class. You could call the function like this (if it is placed in a class called Spawner):

Spawner.create(1000, 1000, createEnemy);
// a new enemy should be created after a second, a thousand times
 

While profiling this peace of code I found it is a bit intensive and could be optimized very simple.

So, what is the problem? This profiler shows the memory usage of a empty flash calling the example Spawner.create function:

I have used FlashPlayer 10.1 (release) and the FlashDevelop for profiling.

See the column ‘count’, which represents the current count of objects. For some reason there are a lot of ‘Functions’ (2000?). There are also 1000x ‘Array’ and ‘SetIntervalTimer’. Now I don’t know what that exactly means, but it is a lot, right? I haven’t used Arrays yet, so setTimeout must be using arrays internally. I think because the intervals are created inside a loop, they are already instantiated and there must be some references to objects too. Inside this test, the createEnemy function is empty, so it is a bit unexpected what happens here.

So I tried to rewrite the code a bit to see if it makes a difference if they are not instantiated at the same time, but create a new interval after one time-out has been called (after each other). It is not very hard to do, so here it is:

public static function create(total:int, interval:int, func:Function, delay:int = 0):void
{
    setTimeout(createNext, delay, total – 1, interval, func, delay);
}

private static function createNext(total:int, interval:int, func:Function, delay:int):void
{
    if (func != null)
    {
        func();
        if (total > 0)
            setTimeout(createNext, interval, total – 1, interval, func, delay);
    }
}

 

The Spawner.create works the same as before, only it is not creating all intervals inside a loop, but passes a reference to the function to the new timeout. Now take a look at the profiler again:

There are less ‘Functions’ and only 11 ‘SetIntervalTimer’, which could be considered as good. Conclusion: If you are using setTimeout, you should be aware how to use it and check if you could improve it in your own app/game.

Tagged with , .

Quick post for all FlashDevelop and flashflowfactory users. I have created a projectfile and templates for flashdevelop.

When you have installed FlashDevelop, it will automatically extract/install itself.

» Download here (flashdevelop flashflowfactory assets.fdz)

Related:
» More flashdevelop assets

Tagged with , .

This article is some training for your JavaScript skills. I love Actionscript , and I am also starting to like JavaScript. However, coding in JavaScript feels like Actionscript 1.0. It’s a pity there aren’t decent editors, especially if you want to write object-oriented-code, which is possible with JavaScript . At the moment I think VisualStudio is the best JavaScript editor, but I really wish there was a tool for JavaScript like FlashDevelop (a clean editor for Actionscript projects) with great intellisense, code completion and snippets etc. But we should not focus on tools, lets focus on the language and get the most out of it. HTML5 is an hot topic today, and it seems using JavaScript is an important part of it, so why not learn more of it? I have seen some stunning HTML5 examples over the last year. As a developer it is very interesting to see how others code JavaScript. By the way; Personally I find it very funny to see how JavaScript has changed it’s ‘image’. Some of us remember the good days in Netscape. JavaScript was .. *kuch* not fast and associated with ugly rainbow mouse pointers and aggressive popup screens. Now it is associated with HTML5, which is supposed to be the future and it will be bright ;) I refuse to put my opinion about this topic here.
I think the ‘image’ of JS has slowly changed after great frameworks like jQuery have reached the developers. jQuery is awesome, I advice to use jQuery as default in all sites/apps.

Anyway, there are (ofcourse) some techniques to code like Actionscript in JavaScript. These snippets have helped me to understand object oriented JavaScript. For too long I did not even tried to learn what was possible with JavaScript because I thought it was a very limited language. Maybe some information is outdated; I am still learning, so please share your feedback.

Object oriented javascript

In javascript it is possible to create classes, public and private vars, getters/setters and there are even constructors. A function could be seen as a class. This is a bit strange at first, but if you use it for a while you will understand. Now lets create our own class right now.

Lets port some stuff of this Color Class to javascript. It has private vars and public functions.

Declare classes

Defining classes is as easy as defining functions, because it is almost the same. After creating an function, you could already make some instances of it. The example below creates a Color class with a public variable called value. After that we create 2 instances of the Color class with some other values.

Note: I use the same code conventions as Actionscript: Classes should be UpperCased, functions/vars should be lowerCased and constants should be FULL_CAPS. Oh and since javascript looks like as1.0, I sometimes use an underscore before private vars :P

function Color( value )
{
    this.value = value || 0;
    alert("Color created with value: " + value)
}

var myRedColor = new Color(0xFF0000); // create instance of Color  (a red one)
var myOrangeColor = new Color(0xFFCC00); // create instance of Color  (an orange one)
alert( myRedColor.value );
alert( myOrangeColor.value );
 

Public / Private

In actionscript it is very useful to use encapsulation, which is a mechanism for restricting access to other objects. The previous+following example should work in all browsers. The difference between public and private vars/functions in javascript can be declared like this:

function Color( value )
{
    // public variable
    this.value = value || 0xFFFFFF; // set default value to 0xFFFFFF for parameter if it isn’t defined

    // private variable
    var _name = "test";

   // public function
   this.getRandomColor = function( )
  {
     return Math.random() * 0xFFFFFF;
  }

  // private function
  function getNiceColor()
  {
     return 0xffcc00;
  }
}

// create instance of Color
var color = new Color(0xFF0000);
alert( color.value ); // returns red color
alert( color.getRandomColor() ); // returns random color

// not possible :
alert( color.getNiceColor() ); error in console; property does not exist, because function is private.
alert( color._name ); // error in console; property does not exist, because variable is private.
 

I think with this principles (maybe in combination with namespaces, see below) you can create clean javascript code.

Packages > Namespaces

Now before using classes in javascript I had some conflicts with function and variable names because there were unwanted duplicates. I have written a little helper tool to use namespaces. It helps to prevent those conflicts. Now it looks more like Actionscript 3, only there is no such thing like ‘imports’. This snippet works in all browsers.

/// create namespace like ‘com.yourcompany.projectname’
function Namespace(namespace)
{
    var parts = namespace.split(".");
    var root = window;
    for(var i = 0; i < parts.length; i++)
    {
        if(typeof root[parts[i]] == "undefined")
        {
            root[parts[i]] = {};
        }
        root = root[parts[i]];
    }
}

// creating my own namespace here
Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function(value) // create class inside package
{
  this.value = value || 0xFFFFFF;
}

var myRedColor =  new nl.stroep.utils.Color(0xff0000);
alert(myRedColor.value);
 

Getters and Setters

Now it is possible to use getters and setters. NOTE (!): Ofcourse this method does not work in IE, so this is pointless but also a bit cool to see how far we could go. Anyway there are 2 ways to define them. Read more about it here. I think the __defineGetter__ way is better; it looks ugly but you still have access to private objects.

Take a look at this getter/setter declaration example. It’s not as clean as AS3 getters/setters but it works like a charm in my browser.

function Color( value )
{

   /* public getter */
   this.__defineGetter__("value", function()
   {
        alert("getter called; current value: " +value);
        return value;
    });
   
   /* public setter */
   this.__defineSetter__("value", function(val)
   {
        alert("setter called; new value: " +val);
        value = val;
    });
   
   // public variable. For a strange reason I have to put this below the get/set definition.
   this.value = value || 0xFFFFFF;
}

// create instance of Color
var color = new Color(0xFF0000);
color.value; // getter
color.value = 0xff0000; // setter
 

Constants

Javascript has a const too, you could use it instead of var. Ofcourse this is not implemented in IE, so it is also pretty pointless to use.

Mix them all

Now lets use namespaces, getters/setters and private/public variables and functions together.
This is a simplified ported version of this Color Class.
With this class you can modify the red,green and blue channels of a color individually. In the original class it is possible to lighten/darken the color too, but for this post I left these functions, because this only illustrates the possibilities of nice OO javascript.

Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function( color )
{   
    /* PUBLIC FUNCTIONS */
   
    this.grayscale = function( val )
    {
        val = val || 0;
        if (val < 0){ val = 0 }
        if (val > 255) { val = 255 }
       
        return (val << 16) | (val << 8 ) | val;
    }
   
    /* PRIVATE FUNCTIONS */
   
    function limit( val, lowerLimit, upperLimit )
    {
        if (val < lowerLimit){ return lowerLimit }
        if (val > upperLimit) { return upperLimit }
        return val;
    }
       
    /* PUBLIC GETTER FUNCTIONS */
   
    this.__defineGetter__("value", function()
    {
        return (_red << 16) | (_green << 8 ) | _blue;
    })
   
    this.__defineGetter__("red", function()
    {
        return _red;
    })
   
    this.__defineGetter__("green", function()
    {
        return _green;
    })
   
    this.__defineGetter__("blue", function()
    {
        return _blue;
    })
   
    /* PUBLIC SETTER FUNCTIONS */
   
    this.__defineSetter__("value", function(val)
    {
        _red  = val >> 16 & 0xFF; // red
        _green  = val  >> 8 & 0xFF; // green
        _blue = val & 0xFF; // blue
       
        _value = val;
    })
   
    this.__defineSetter__("red", function(val)
    {
        _red = val;
        _red = limit( _red, 0, 255 );
    })
   
    this.__defineSetter__("green", function(val)
    {
        _green = val;
        _green = limit( _green, 0, 255 );
    })
   
    this.__defineSetter__("blue", function(val)
    {
        _blue = val;
        _blue = limit( _blue, 0, 255 );
    })
   
    /* PRIVATE VARIABLES */
    var _value = color;
    var _red;
    var _green;
    var _blue;
   
    /* PUBLIC VARIABLES */
    this.value = _value;
   
};
 

With this javascript class, you could use it like this:

var color = new nl.stroep.utils.Color(0xFFCC00) // define orange.
color.green = 0; // remove green.. now it is red..
color.blue = 255; // add some blue.. now it is purple..
alert(color.value.toString(16)) // alerts FF00FF and that is purple.
 

Hope you enjoyed this article. Feel free to share or comment.

Tagged with , , , , .

Chain Tween (1)

October 30th, 2010, under actionscript, Code snippets.

ChainPrevious year I was working on a little class called Chain. Chain is a delayed function-calling util class for AS3. Now I was already working at a updated version which could animate too (see this tweet from last year). Basically it has become a small tween engine. You have to know there are much better tween engines, like TweenLite, Tweener, eaze tween, gtween etc.. So you don’t need a new tween engine, and definitely not this one :) I just love to share some thoughts.

I just finished this to see how far I could come and where I have to deal with by creating such an engine. It is just fun to develop classes which will bring you to a higher level of coding, because I really want to become an actionscript sensai master or something. When starting the animation part, I was very inspired by this post, which has the same idea of combining jQuery-syntax-style with tweening, which I was already using in Chain.
Making a class chainable is very easy, you just have to return the class instance on every public function, like this:

package
{
  public class ExampleChain
  {
    public function add():ExampleChain
    {
       trace(this, "saying hi!")
       return this;
    }
  }
}
 

This already allows you to do this:

var chain:ExampleChain = new ExampleChain();
chain.add().add().add().add();
 

I think this is very powerful and we should use more chaining.

Anyway, Chain was originally created to make delayed function calling. I wrapped code around this feature, so it is still usable like it was intended, only I improved some functions and added tweening. You can pass a complete handler to the play() function. And it is also possible to reverse the full chain, even with animation.

Here again, the original simple usage

var myChain:Chain = new Chain();    
myChain.add(one, 2000)
  .add(two, 500)
  .add(three, 1000)
  .play(3, onChainComplete);  // play 3 times

// some functions
function one():void { trace("one") }
function two():void { trace("two") }
function three():void { trace("three") }
function onChainComplete():void {
    trace("done.");
    myChain.destroy();
}
/* trace output:
one two three one two three one two three done.
*/

 

Animated chain example

var myChain:Chain = new Chain();    
myChain
   .animate(myMc, {x:300,y:100}, 700, Easing.elasticInOut)
   .wait(200)
   .animate(myMc2, {rotation:100, alpha:0.5}, 500, Easing.quartIn)
   .wait(200)
   .play(2, onChainComplete); // play 2 times

function onChainComplete():void {
   trace("done.");
    myChain.destroy();
}
 

As you can see, you can still chain things, it animates multiple movieclips, and it can be played multiple times. It is very readable, which I really like. It works also in reversed order too, so you can reverse the full animation (pointless but cool)!

If you don’t want to animate, but instantly apply settings to a displayObject,
you can use apply(mc, {vars}), of couse this equals animate(mc,{vars},0) but it is more elegant.

To control the Chain, you have can use:
stop() Stop playing, use doContinue to play futher from current point
doContinue() Continue playing after a stop
reset() Reset indexes, start from first point. If reversed, start at last point

So how does it work? Well it is still based on the same old add() function. When you call the animate() function, internally, it is collecting the properties of the tween. Then it is calling the add() function, with a reference to a protected function playTween(), which is always the same. So when you play the chain, it just calling a local function every time, which handles the animation.

For now, I don’t have any special properties; no auto-alpha, no short-rotation, blurfilters or tinting etc. You can only animate properties of movieclips.

So how does tweening (animation over time) work? This is the formula I am using:

_target[property.name] = property.startValue + ((property.endValue – property.startValue) * _easeFunc(currentTime – _startTime) / _duration);

This needs a little explanation. For example: When you add {x:100} as object to Chain for animation, “x” is the property.name, and 100 is the property.endValue. I am also getting current “x” value of the displayobject (which should move); this is the property.startvalue. Imaging this is currently 75.
If you would write down the values into the formula, it looks like this:

myMc["x"] = 75 + ((10075) * _easeFunc(currentTime – _startTime) / _duration));

Now, as you can see, this is more readable. The only thing that is still vague is the ease function. Now I have to say this was a bit hard for me to understand at the first time, but it became very clear when I did understand what is does. I have read the book ‘Making things move’ from Keith Peters (aka bit-101), which is a great reference and eye opening book for programmatic animation, trigonometry and other cool stuff. There is a chapter where animation over time is explained, which was really helpful creating the tween engine, and this time calculation. Now the time calculating returns a ratio, which is needed for the easing functions. I also studied some famous other tween engines; most of them use basically the same formula. By the way, the easing equations are used from Robert Penner.

Now, I really wanted to reverse the animations too. After some headache, the solutions was very simple. The time calculation is a value between 0-1, so I did 1 minus the time ratio :)

_target[property.name] = property.startValue + ((property.endValue – property.startValue) * _easeFunc(1(currentTime – _startTime) / _duration));

Another problem I had to deal with was the fact that animating 1 thing at a time is very boring. So I invented the animateAsync(), which works almost exactly like the animate(), only you could pass the duration and the delay as separate values. So you can move a clip for 700 milliseconds, and call the next chained item after 75 milliseconds. To compare: when using the animate() function, if you move an item for 700 milliseconds, it will take 700 milliseconds when calling the next chained item. This could cause strange behaviors and isn’t easy to manage (especially when you want to wait till all animations are done), but I its a nice feature I think. Again, even the async’s can be played in reversed order.

var myChain:Chain = new Chain();    
myChain
   .animateAsync(myMc, {x:300,y:100}, 700, 10, Easing.elasticInOut)
   .animate(myMc2, {rotation:100, alpha:0.5}, 500, Easing.quartIn)
   .wait(200)
   .play(2, onChainComplete); // play 2 times

function onChainComplete():void {
   trace("done.");
    myChain.destroy();
}
 

To clear all references, you should call the myChain.destroy(); function. This clears the references to all added functions, and clears the internal tween list.

update 02/11/2010:
- added show/hide/rotate function
- added shortRotation option
- added scale (no need to define scaleX and scaleY separately)
- optimized chain; chain items are stored by duration inside dictionary to save lots instances (where duration is the same)
- added Chain.create for fast creation of an instance
- updated apply function (extra param; apply on start)
- several coding style fixes
- added destroyOnComplete to animate() function

So if you are interested in the code, you can find it inside my googlecode:
» Chain Tween sources

Tagged with , , .

I hate removing listeners in AS3. So I created a work-around to autoremove them :) I know there are already some solutions for this, but some of them requires a complete new event system and it is just fun to create your own sources. This class overrides the default behavior of the addEventListener function. It stores references of the listeners inside a Dictionary. The class it selfs listens to the REMOVED_FROM_STAGE event, and when it is removed, then it removes all stored events.

UPDATE 11-10-2010: This code below is a bit outdated.
You’d better use this EventManagedSprite and this EventRemover. BTW: This is all included in FlashFlowFactory. This lightweight framework helps you to easily setup a flash website.

package nl.stroep.display
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.utils.Dictionary;
    /**
     * Simple event managing sprite which automatically removes eventlisteners when the sprite is removed from stage. This class should be extended.
     * @author Mark Knol
     */

    public class EventManagedSprite extends Sprite
    {
        private var eventsList:/*Array*/Dictionary = new Dictionary();
       
        public function EventManagedSprite()
        {
            super.addEventListener(Event.REMOVED_FROM_STAGE, onRemoveEventManagedSprite)
        }
       
        private function onRemoveEventManagedSprite(e:Event):void
        {
            super.removeEventListener(Event.REMOVED_FROM_STAGE, onRemoveEventManagedSprite);
           
            for (var type:String in eventsList)
            {
                var events:Array = eventsList[type] as Array;
               
                for (var i:int = 0; i < events.length; i++)
                {
                    var eventObject:EventObject = events[i];
                    super.removeEventListener( type, eventObject.listener, eventObject.useCapture );
                   
                    //trace("Auto removed listener ", type, eventObject.listener, "from", this);
                   
                    eventObject.listener = null;
                    eventObject = null;
                   
                    if (events.length == 0)
                        delete eventsList[type];
                }
            }
        }
       
        override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
        {
            super.addEventListener(type, listener, useCapture, priority, useWeakReference);
           
            if (!eventsList[ type ])
            {
                eventsList[ type ] = [ new EventObject( listener, useCapture ) ];
            }
            else
            {
                eventsList[ type ].push( new EventObject( listener, useCapture ) );
            }
        }
    }
}

final internal class EventObject
{
    public var listener:Function
    public var useCapture:Boolean
   
    public final function EventObject ( listener:Function, useCapture:Boolean ):void
    {
        this.listener = listener;
        this.useCapture = useCapture;
    }
}

Make sure every class you add listeners extends this class to make the most out of it. Otherwise you just need to remove the listeners yourself. Let me know what you think about it.

Disclaimer: This class does not detect the eventlisteners on the children of the class. These children should extend the EventManagedSprite class too, otherwise you should remove it manually.

Tagged with , , .