Skip to content

Commit

Permalink
fixed event emitter to alloow removing all listeners for a single tag
Browse files Browse the repository at this point in the history
  • Loading branch information
AlmirKadric committed Oct 25, 2016
1 parent cf3f124 commit 2e9b9e4
Showing 1 changed file with 26 additions and 15 deletions.
41 changes: 26 additions & 15 deletions EventEmitter/EventEmitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,25 @@ namespace Wizcorp.MageSDK.Event
public class EventEmitter<T>
{
//
private Dictionary<string, object> eventTags = new Dictionary<string, object>();
private EventHandlerList eventsList = new EventHandlerList();
private Dictionary<string, EventHandlerList> tagListMap = new Dictionary<string, EventHandlerList>();

//
public void On(string eventTag, Action<object, T> handler)
{
if (!eventTags.ContainsKey(eventTag))
if (!tagListMap.ContainsKey(eventTag))
{
eventTags.Add(eventTag, new object());
tagListMap.Add(eventTag, new EventHandlerList());
}

eventsList.AddHandler(eventTags[eventTag], handler);
tagListMap[eventTag].AddHandler(null, handler);
}

//
public void Once(string eventTag, Action<object, T> handler)
{
Action<object, T> handlerWrapper = null;
handlerWrapper = (obj, arguments) => {
eventsList.RemoveHandler(eventTags[eventTag], handlerWrapper);
tagListMap[eventTag].RemoveHandler(null, handlerWrapper);
handler(obj, arguments);
};

Expand All @@ -36,12 +35,12 @@ public void Once(string eventTag, Action<object, T> handler)
//
public void Emit(string eventTag, object sender, T arguments)
{
if (!eventTags.ContainsKey(eventTag))
if (!tagListMap.ContainsKey(eventTag))
{
return;
}

var execEventList = (Action<object, T>)eventsList[eventTags[eventTag]];
var execEventList = (Action<object, T>)tagListMap[eventTag][null];
if (execEventList != null)
{
execEventList(sender, arguments);
Expand All @@ -56,23 +55,35 @@ public void Emit(string eventTag, T arguments)
//
public void Off(string eventTag, Action<object, T> handler)
{
if (!eventTags.ContainsKey(eventTag))
if (!tagListMap.ContainsKey(eventTag))
{
return;
}

eventsList.RemoveHandler(eventTags[eventTag], handler);
tagListMap[eventTag].RemoveHandler(null, handler);
}

//
public void RemoveTagListeners(string eventTag)
{
if (!tagListMap.ContainsKey(eventTag))
{
return;
}

tagListMap[eventTag].Dispose();
tagListMap[eventTag] = new EventHandlerList();
}

//
public void RemoveAllListeners()
{
// Destroy all event handlers
eventsList.Dispose();
eventsList = new EventHandlerList();
foreach (KeyValuePair<string, EventHandlerList> entry in tagListMap)
{
entry.Value.Dispose();
}

// Destroy all event tags
eventTags = new Dictionary<string, object>();
tagListMap = new Dictionary<string, EventHandlerList>();
}
}
}

0 comments on commit 2e9b9e4

Please sign in to comment.