-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventEmitter.cs
97 lines (95 loc) · 2.66 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
93
94
95
96
97
using System.Collections;
using System.Collections.Generic;
using System;
namespace CryvisNet
{
public class EventEmitter<L, T>
{
private Dictionary<L, List<Action<T>>> handlers = new Dictionary<L, List<Action<T>>>();
private Dictionary<L, List<Action<T>>> onceHandlers = new Dictionary<L, List<Action<T>>>();
public EventEmitter()
{
handlers = new Dictionary<L, List<Action<T>>>();
}
public void on(L ev, Action<T> callback)
{
if (!handlers.ContainsKey(ev))
{
handlers[ev] = new List<Action<T>>();
}
handlers[ev].Add(callback);
}
public void once(L ev, Action<T> callback)
{
if (!onceHandlers.ContainsKey(ev))
{
onceHandlers[ev] = new List<Action<T>>();
}
onceHandlers[ev].Add(callback);
}
public void off(L ev, Action<T> callback)
{
if (!handlers.ContainsKey(ev))
{
return;
}
List<Action<T>> l = handlers[ev];
if (!l.Contains(callback))
{
return;
}
l.Remove(callback);
if (l.Count == 0)
{
handlers.Remove(ev);
}
}
public void emit(L name, T data)
{
if (!handlers.ContainsKey(name))
{
if (name.GetType() == typeof(Exception))
{
throw name as Exception;
}
return;
}
foreach (Action<T> handler in this.handlers[name])
{
try
{
handler(data);
}
catch (Exception ex)
{
throw ex;
}
}
if (!onceHandlers.ContainsKey(name))
{
if (name.GetType() == typeof(Exception))
{
throw name as Exception;
}
return;
}
foreach (Action<T> onceHandler in this.onceHandlers[name])
{
try
{
onceHandler(data);
this.onceHandlers.Remove(name);
}
catch (Exception ex)
{
throw ex;
}
}
}
public void removeAllListeners()
{
handlers = new Dictionary<L, List<Action<T>>>();
onceHandlers = new Dictionary<L, List<Action<T>>>();
}
}
}