Last active
September 21, 2018 13:32
-
-
Save shreve/fcbc6e49da9cb8735eedf423a9e9d583 to your computer and use it in GitHub Desktop.
Callback List
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
using System; | |
using System.Collections.Generic; | |
using ActionList = System.Collections.Generic.List<System.Action>; | |
using ActionDict = System.Collections.Generic | |
.Dictionary<string, System.Collections.Generic.List<System.Action>>; | |
// A list of callbacks to easily implement the observable pattern | |
// Attach to any class as a public static for an easy interface | |
// | |
// Foreign classes: | |
// Class.callbacks.On("event", _callback); | |
// | |
// To trigger: | |
// callbacks.RunFor("event"); | |
// | |
public class CallbackList { | |
ActionDict callbacks = new ActionDict(); | |
public void On(string eventName, Action callback) { | |
if (!callbacks.ContainsKey(eventName)) { | |
callbacks[eventName] = new ActionList(); | |
} | |
if (callbacks[eventName].IndexOf(callback) != -1) { return; } | |
callbacks[eventName].Add(callback); | |
} | |
public List<Action> For(string eventName) { | |
if (!callbacks.ContainsKey(eventName)) { | |
return new ActionList(); | |
} | |
return callbacks[eventName]; | |
} | |
public void RunFor(string eventName) { | |
if (callbacks.ContainsKey(eventName)) { | |
foreach (Action callback in callbacks[eventName]) { | |
if (callback != null) { callback(); } | |
} | |
} | |
} | |
public void Clear() { | |
callbacks.Clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment