View Single Post
Nutrox's Avatar Nutrox Nutrox is offline Super Moderator 17 Creative Assets 2006-11-05 #6 Old  
005 - Multiple onEnterFrame Functions
 
If you want to be able to quickly and easily assign multiple functions to a movie clip's onEnterFrame event then the following code should give you something to play with.

ActionScript Code:
  1. var frameListeners:Array = [];
  2.  
  3. function addFrameListener(func:Function):Void {
  4.     removeFrameListener(func);
  5.     frameListeners.push(func);
  6.     if (!this.onEnterFrame) {
  7.         this.onEnterFrame = fireFrameListeners;
  8.     }
  9. }
  10.  
  11. function removeFrameListener(func:Function):Void {
  12.     var i:Number = frameListeners.length;
  13.     while (i--) {
  14.         if (frameListeners[i] == func) {
  15.             delete frameListeners.splice(i, 1);
  16.             break;
  17.         }
  18.     }
  19.     if (!frameListeners.length) {
  20.         this.onEnterFrame = null;
  21.     }
  22. }
  23.  
  24. function fireFrameListeners():Void {
  25.     var i:Number = 0;
  26.     var n:Number = frameListeners.length;
  27.     while (i < n) {
  28.         frameListeners[i++]();
  29.     }
  30. }
With those functions placed on the movie clip's timeline you can now add (and remove) your functions. All of the assigned functions will be called on each frame in the order you add&nbsp;them.

ActionScript Code:
  1. addFrameListener(functionOne);
  2. addFrameListener(functionTwo);
  3.  
  4. //
  5.  
  6. function functionOne():Void {
  7.    trace("function one");
  8. }
  9.  
  10. function functionTwo():Void {
  11.    trace("function two");
  12. }
That would result in the following trace on each frame:

-- function one
-- function two

Removing functions is done in the same way.

ActionScript Code:
  1. removeFrameListener(functionTwo);
Keep in mind that these functions will use the movie clip's onEnterFrame event handler so if you manually assign a function to it then things will go pear shaped. For example, you shouldn't do something like&nbsp;this:

ActionScript Code:
  1. addFrameListener(someFunction);
  2.  
  3. this.onEnterFrame = function():Void {
  4.    //
  5. }