From 2e9b9e42253268d203bc86e5fe0bb744b1ba2e01 Mon Sep 17 00:00:00 2001 From: Almir Kadric Date: Tue, 25 Oct 2016 19:05:08 +0900 Subject: [PATCH] fixed event emitter to alloow removing all listeners for a single tag --- EventEmitter/EventEmitter.cs | 41 +++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/EventEmitter/EventEmitter.cs b/EventEmitter/EventEmitter.cs index 8db7f0a..f703d04 100644 --- a/EventEmitter/EventEmitter.cs +++ b/EventEmitter/EventEmitter.cs @@ -7,18 +7,17 @@ namespace Wizcorp.MageSDK.Event public class EventEmitter { // - private Dictionary eventTags = new Dictionary(); - private EventHandlerList eventsList = new EventHandlerList(); + private Dictionary tagListMap = new Dictionary(); // public void On(string eventTag, Action 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); } // @@ -26,7 +25,7 @@ public void Once(string eventTag, Action handler) { Action handlerWrapper = null; handlerWrapper = (obj, arguments) => { - eventsList.RemoveHandler(eventTags[eventTag], handlerWrapper); + tagListMap[eventTag].RemoveHandler(null, handlerWrapper); handler(obj, arguments); }; @@ -36,12 +35,12 @@ public void Once(string eventTag, Action handler) // public void Emit(string eventTag, object sender, T arguments) { - if (!eventTags.ContainsKey(eventTag)) + if (!tagListMap.ContainsKey(eventTag)) { return; } - var execEventList = (Action)eventsList[eventTags[eventTag]]; + var execEventList = (Action)tagListMap[eventTag][null]; if (execEventList != null) { execEventList(sender, arguments); @@ -56,23 +55,35 @@ public void Emit(string eventTag, T arguments) // public void Off(string eventTag, Action 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 entry in tagListMap) + { + entry.Value.Dispose(); + } - // Destroy all event tags - eventTags = new Dictionary(); + tagListMap = new Dictionary(); } } }