Created
January 31, 2014 06:51
-
-
Save keless/8727613 to your computer and use it in GitHub Desktop.
C# EventDispatcher (AS3 style) implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//TODO: determine if C# delegates cause reference counting on target object | |
public delegate void EventDispatcherDelegate( object evtData ); | |
public interface IEventDispatcher | |
{ | |
void addListener (string evtName, EventDispatcherDelegate callback); | |
void dropListener (string evtName, EventDispatcherDelegate callback); | |
void dispatch (string evtName, object evt) ; | |
} | |
public class EventDispatcher : IEventDispatcher | |
{ | |
Dictionary<string,List<EventDispatcherDelegate>> m_listeners = new Dictionary<string, List<EventDispatcherDelegate>>(); | |
public void addListener( string evtName, EventDispatcherDelegate callback ) | |
{ | |
List<EventDispatcherDelegate> evtListeners = null; | |
if (m_listeners.TryGetValue (evtName, out evtListeners)) | |
{ | |
evtListeners.Remove(callback); //make sure we dont add duplicate | |
evtListeners.Add(callback); | |
} else { | |
evtListeners = new List<EventDispatcherDelegate>(); | |
evtListeners.Add(callback); | |
m_listeners.Add(evtName, evtListeners); | |
} | |
} | |
public void dropListener( string evtName, EventDispatcherDelegate callback ) | |
{ | |
List<EventDispatcherDelegate> evtListeners = null; | |
if (m_listeners.TryGetValue (evtName, out evtListeners)) | |
{ | |
for( int i=0;i< evtListeners.Count; i++) | |
{ | |
evtListeners.Remove(callback); | |
} | |
} | |
} | |
public void dispatch( string evtName, object evt ) | |
{ | |
//FIXME: might need to COPY the list<dispatchers> here so that an | |
// event listener that results in adding/removing listeners does | |
// not invalidate this for loop | |
List<EventDispatcherDelegate> evtListeners = null; | |
if (m_listeners.TryGetValue (evtName, out evtListeners)) | |
{ | |
for( int i=0;i< evtListeners.Count; i++) | |
{ | |
evtListeners[i](evt); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment