-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathJsStyleEventEmitter.cs
More file actions
97 lines (88 loc) · 2.77 KB
/
JsStyleEventEmitter.cs
File metadata and controls
97 lines (88 loc) · 2.77 KB
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HowProgrammingWorks.CSharpEvents
{
public class JsStyleEventEmitter
{
private readonly Dictionary<string, List<Action<object>>> _eventsDictionary;
public JsStyleEventEmitter()
{
this._eventsDictionary = new Dictionary<string, List<Action<object>>>();
}
public void On(string name, Action<object> action)
{
List<Action<object>> subscribedActions;
if (_eventsDictionary.TryGetValue(name, out subscribedActions))
{
subscribedActions.Add(action);
}
else
{
_eventsDictionary.Add(name, new List<Action<object>> { action });
}
}
public void Emit(string name, object data)
{
if (name == "*")
{
foreach (var currentEvent in _eventsDictionary)
{
foreach (var action in currentEvent.Value)
{
action(data);
}
}
}
else
{
List<Action<object>> subscribedActions;
if (!_eventsDictionary.TryGetValue(name, out subscribedActions))
{
Console.WriteLine("Action does not exist");
}
else
{
foreach (var action in subscribedActions)
{
action(data);
}
}
}
}
public void RemoveListener(string name, Action<object> action)
{
List<Action<object>> subscribedActions;
if (!this._eventsDictionary.TryGetValue(name, out subscribedActions))
{
Console.WriteLine("Action does not exist");
}
else
{
var currentEvent = subscribedActions.Exists(e => e == action);
if (currentEvent == false)
{
Console.WriteLine("Event does not exist");
}
else
{
subscribedActions.Remove(action);
}
}
}
public void RemoveAllListeners(string name)
{
List<Action<object>> subscribedActions;
if (!this._eventsDictionary.TryGetValue(name, out subscribedActions))
{
Console.WriteLine("Action does not exist");
}
else
{
subscribedActions.RemoveAll(x => x != null);
}
}
}
}