This repository has been archived by the owner on Mar 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventEmitter.cs
92 lines (83 loc) · 2.88 KB
/
EventEmitter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace PusherClient
{
/// <summary>
/// Class used to Bind and unbind from events
/// </summary>
public class EventEmitter
{
private readonly Dictionary<string, List<Action<dynamic>>> _eventListeners = new Dictionary<string, List<Action<dynamic>>>();
private readonly List<Action<string, dynamic>> _generalListeners = new List<Action<string, dynamic>>();
/// <summary>
/// Binds to a given event name
/// </summary>
/// <param name="eventName">The Event Name to listen for</param>
/// <param name="listener">The action to perform when the event occurs</param>
public void Bind(string eventName, Action<dynamic> listener)
{
if(_eventListeners.ContainsKey(eventName))
{
_eventListeners[eventName].Add(listener);
}
else
{
var listeners = new List<Action<dynamic>> {listener};
_eventListeners.Add(eventName, listeners);
}
}
/// <summary>
/// Binds to ALL event
/// </summary>
/// <param name="listener">The action to perform when the any event occurs</param>
public void BindAll(Action<string, dynamic> listener)
{
_generalListeners.Add(listener);
}
/// <summary>
/// Removes the binding for the given event name
/// </summary>
/// <param name="eventName">The name of the event to unbind</param>
public void Unbind(string eventName)
{
_eventListeners.Remove(eventName);
}
/// <summary>
/// Remove the action for the event name
/// </summary>
/// <param name="eventName">The name of the event to unbind</param>
/// <param name="listener">The action to remove</param>
public void Unbind(string eventName, Action<dynamic> listener)
{
if(_eventListeners.ContainsKey(eventName))
{
_eventListeners[eventName].Remove(listener);
}
}
/// <summary>
/// Remove All bindings
/// </summary>
public void UnbindAll()
{
_eventListeners.Clear();
_generalListeners.Clear();
}
internal void EmitEvent(string eventName, string data)
{
var obj = JsonConvert.DeserializeObject<dynamic>(data);
// Emit to general listeners regardless of event type
foreach (var action in _generalListeners)
{
action(eventName, obj);
}
if (_eventListeners.ContainsKey(eventName))
{
foreach (var action in _eventListeners[eventName])
{
action(obj);
}
}
}
}
}