10
Dec 07

Actionscript 3.0 Scopeless Event Dispatcher

I've had this code around since my as 2.0 devirginizing(awhile ago..ahaha) So I decided to transfer it into AS3. It's a very simple class, but what it does is pretty cool, basically you can have events that aren't tied to specific classes or objects. Basically class A can talk to class D without knowing who class D is... just knowing it has to send out an event... if that makes sense. While i think the way Events especially in AS3 are great, and i will use them more often than not... its always nice to have something to fall back on when you need 2 or more things to talk without necessarily knowing who they are. Heres my source :

Actionscript:
  1. package com.rLuce.utils {
  2. public class EventManager {
  3. /*
  4. * Event Manager: Ryan Luce
  5. * Methods:
  6. * addEventListener : Adds an event to the list
  7. * dispatchEvent : Calls all functions related to that Event, and passes an object(or Event) if necessary
  8. *
  9. * */
  10.  
  11. private static var Events:Array = [];
  12. //Standard addeventlistener
  13. public static function addEventListener(eventName:String, fncRef:Function):void
  14. {
  15. if(Events[eventName] != null) {
  16. Events[eventName].push(fncRef);
  17. } else {
  18. Events[eventName] = [];
  19. Events[eventName].push(fncRef);
  20. }
  21. }
  22.  
  23. public static function removeEventListener(eventName:String, fncRef:Function):void
  24. {
  25. //this hasn't been tested i think i need to slice(a, (a + 1)) if my logic is even right
  26. //haven't had to get into this and this was a quick port from my as2 class which was a bit different
  27. for(var a:Number = 0; a <Events[eventName].length; a++)
  28. if(Events[eventName] == fncRef)
  29. trace("Removing: " + Events[eventName].slice(a,a));
  30. }
  31.  
  32. public static function dispatchEvent(eventName:String, obj:*= null):void
  33. {
  34. if(Events[eventName] != null)
  35. for(var a = 0; a <Events[eventName].length; a++)
  36. Events[eventName][a](obj);
  37. }
  38. }
  39. }

Usage for this is pretty simple, just like the normal event dispatcher. I haven't tested this thoroughly yet, and will this coming week... will update it when i have time. I'll post a file up here as well with the class... to make it a bit easier.

Edit: Here you go: (right click save as)
EventManager.as


Copyright © 2010 p0wn.net == Ryan Luce
Proudly powered by WordPress, Free WordPress Themes, and Linux Hosting