-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEventRouter.cs
More file actions
executable file
·410 lines (380 loc) · 12.6 KB
/
Copy pathEventRouter.cs
File metadata and controls
executable file
·410 lines (380 loc) · 12.6 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright (c) 2009-2012 David Koontz, Dan Peschman, and Logan Barnett
// Please direct any bugs/comments/suggestions to david@koontzfamily.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Class for broadcasting messages to subscribers. Clients of the EventRouter register
/// themselves by calling Subscribe and passing in the event they are interested in along with
/// a delegate to be called back when the event is received. Events are published via the
/// Publish method which allows arbitrary data to be passed along with the event to be interpreted
/// by the event receiver. Events do not have to be pre-defined.
///
/// Publish and Subscribe methods also have an optional id parameter which will filter the events
/// sent to just those that match the provided id. Subscribing to an event with no id will result
/// in receiving all events of the specified type.
/// </summary>
/// <example>
/// Example of a simple publish and subscribe class, not using any id filtering.
///
/// Sender.cs
/// <code>
/// public enum SenderEvent {
/// Test
/// }
///
/// public class Sender {
/// public void Send() {
/// EventRouter.Publish(SenderEvent.Test, "Hello World");
/// }
/// }
/// </code>
///
/// Receiver.cs
/// <code>
/// public class Receiver {
/// public Receiver() {
/// EventRouter.Subscribe(SenderEvent.Test, OnSenderEvent);
/// }
///
/// void OnSenderEvent(EventRouter.Event evt) {
/// if(evt.HasData) {
/// Console.WriteLine("Received event: " + evt.Type + " with data: " + evt.GetData<string>(0));
/// }
/// else {
/// Console.WriteLine("Received event: " + evt.Type + " with no data");
/// }
/// }
/// }
/// </code>
/// </example>
///
/// <example>
/// Example of a publish and subscribe using id's to filter specific messages.
///
/// Sender.cs
/// <code>
///
/// public enum SenderEvent {
/// Test
/// }
///
/// public class Sender {
/// public void SendA() {
/// EventRouter.Publish("A", SenderEvent.Test);
/// }
///
/// public void SendB() {
/// EventRouter.Publish("B", SenderEvent.Test);
/// }
/// }
/// </code>
///
/// Receiver.cs
/// <code>
///
/// public class Receiver {
/// public Receiver() {
/// EventRouter.Subscribe("A", SenderEvent.Test, OnSenderEventA);
/// EventRouter.Subscribe("B", SenderEvent.Test, OnSenderEventB);
/// }
///
/// void OnSenderEventA(EventRouter.Event evt) {
/// Console.WriteLine("Received SenderEvent.Test with id 'A'");
/// }
///
/// void OnSenderEventB(EventRouter.Event evt) {
/// Console.WriteLine("Received SenderEvent.Test with id 'B'");
/// }
/// }
/// </code>
/// </example>
public class EventRouter
{
/// <summary>
/// Event data class, passed in to the subscriber whenever an event occours.
/// </summary>
public class Event
{
public string Type;
public string Id;
public object[] Data;
public bool HasData
{
get { return Data != null && Data.Length > 0; }
}
public T GetData<T>(int index)
{
return (T)Data[index];
}
}
public delegate void Handler(Event e);
public static bool LogEvents = false;
static Dictionary<string, Dictionary<string, Handler>> handlers = new Dictionary<string, Dictionary<string, Handler>>();
static Queue<Event> queuedEvents = new Queue<Event>();
/// <summary>
/// Subscribe to the event specified by evt. Pass in a delegate to be called back when the event occurs.
/// </summary>
/// <param name='evt'>
/// The event enumeration value.
/// </param>
/// <param name='h'>
/// The delegate to be called when the event occurs.
/// </param>
public static void Subscribe(Enum evt, Handler h)
{
Subscribe("", EnumValueToString(evt), h);
}
/// <summary>
/// Subscribe to the event specified by evt filtered by the specified id. Pass in a delegate to be called back when the event occurs.
/// </summary>
/// <param name='id'>
/// The id of the event
/// </param>
/// <param name='evt'>
/// The event enumeration value.
/// </param>
/// <param name='h'>
/// The delegate to be called when the event occurs.
/// </param>
public static void Subscribe(string id, Enum evt, Handler h)
{
Subscribe(id, EnumValueToString(evt), h);
}
/// <summary>
/// Subscribe to the event specified by evt. Pass in a delegate to be called back when the event occurs.
/// </summary>
/// <param name='id'>
/// The string representing the id.
/// </param>
/// <param name='evt'>
/// The string representing the event.
/// </param>
/// <param name='h'>
/// The delegate to be called when the event occurs.
/// </param>
public static void Subscribe(string id, string evt, Handler h)
{
if (!handlers.ContainsKey(evt))
{
handlers.Add(evt, new Dictionary<string, Handler>());
}
if (!handlers[evt].ContainsKey(id))
{
handlers[evt].Add(id, null);
}
handlers[evt][id] += h;
}
/// <summary>
/// Subscribe to the event specified by evt. Pass in a delegate to be called back when the event occurs.
/// </summary>
/// <param name='evt'>
/// The string representing the event.
/// </param>
/// <param name='h'>
/// The delegate to be called when the event occurs.
/// </param>
public static void Subscribe(string evt, Handler h)
{
Subscribe("", evt, h);
}
/// <summary>
/// Unsubscribe the specified delegate from the event.
/// </summary>
/// <param name='id'>
/// The id of the event
/// </param>
/// <param name='evt'>
/// The event enumeration value.
/// </param>
/// <param name='h'>
/// The delegate to be removed from the event handlers.
/// </param>
public static void Unsubscribe(string id, Enum evt, Handler h)
{
Unsubscribe(id, EnumValueToString(evt), h);
}
/// <summary>
/// Unsubscribe the specified delegate from the event.
/// </summary>
/// <param name='evt'>
/// The event enumeration value.
/// </param>
/// <param name='h'>
/// The delegate to be removed from the event handlers.
/// </param>
public static void Unsubscribe(Enum evt, Handler h)
{
Unsubscribe(EnumValueToString(evt), h);
}
/// <summary>
/// Unsubscribe the specified delegate from the event.
/// </summary>
/// <param name='evt'>
/// The string representing the event.
/// </param>
/// <param name='h'>
/// The delegate to be removed from the event handlers.
/// </param>
public static void Unsubscribe(string evt, Handler h)
{
Unsubscribe("", evt, h);
}
/// <summary>
/// Unsubscribe the specified delegate from the event.
/// </summary>
/// <param name='id'>
/// The string representing the id.
/// </param>
/// <param name='evt'>
/// The string representing the event.
/// </param>
/// <param name='h'>
/// The delegate to be removed from the event handlers.
/// </param>
public static void Unsubscribe(string id, string evt, Handler h)
{
if (handlers.ContainsKey(evt) && handlers[evt].ContainsKey(id))
{
handlers[evt][id] -= h;
if (handlers[evt][id] == null) handlers.Remove(evt);
}
}
/// <summary>
/// Publish the specified event with extra data.
/// </summary>
/// <param name='id'>
/// The string representing the object.
/// </para>
/// <param name='evt'>
/// The string representing the event.
/// </param>
/// <param name='data'>
/// An arbitrary params array of objects to be interpreted by the receiver of the event.
/// </param>
public static void Publish(string id, string evt, params object[] data)
{
#if UNITY_ENGINE
if (LogEvents) UnityEngine.Debug.Log(string.Format("Event Published: '{0}' with id: '{1}' and {2} parameters", evt, id, data.Length));
#else
if (LogEvents) Console.WriteLine(string.Format("Event Published: '{0}' with id: '{1}' and {2} parameters", evt, id, data.Length));
#endif
ProcessEvent(id, evt, data);
while (queuedEvents.Count > 0)
{
var queuedEvent = queuedEvents.Dequeue();
ProcessEvent(queuedEvent.Id, queuedEvent.Type, queuedEvent.Data);
}
}
/// <summary>
/// Publish the specified event with extra data.
/// </summary>
/// <param name='evt'>
/// The string representing the event.
/// </param>
/// <param name='data'>
/// An arbitrary params array of objects to be interpreted by the receiver of the event.
/// </param>
public static void Publish(string evt, params object[] data)
{
Publish("", evt, data);
}
/// <summary>
/// Publish the specified event with extra data.
/// </summary>
/// <param name='id'>
/// The string representing the object.
/// </para>
/// <param name='evt'>
/// The event enumeration value.
/// </param>
/// <param name='data'>
/// An arbitrary params array of objects to be interpreted by the receiver of the event.
/// </param>
public static void Publish(string id, Enum evt, params object[] data)
{
Publish(id, EnumValueToString(evt), data);
}
/// <summary>
/// Publish the specified event with extra data.
/// </summary>
/// <param name='evt'>
/// The event enumeration value.
/// </param>
/// <param name='data'>
/// An arbitrary params array of objects to be interpreted by the receiver of the event.
/// </param>
public static void Publish(Enum evt, params object[] data)
{
Publish(EnumValueToString(evt), data);
}
public static void Queue(string id, string evt, params object[] data)
{
var e = new Event { Type = evt, Id = id };
if (data != null && data.Length > 0) e.Data = data;
queuedEvents.Enqueue(e);
}
public static void Queue(string evt, params object[] data)
{
Queue(string.Empty, evt, data);
}
public static void Queue(string id, Enum evt, params object[] data)
{
Queue(id, EnumValueToString(evt), data);
}
public static void Queue(Enum evt, params object[] data)
{
Queue(string.Empty, EnumValueToString(evt), data);
}
/// <summary>
/// Clear all event subscribers, used primarily when switching or resetting a level.
/// </summary>
public static void Clear()
{
handlers.Clear();
}
static void ProcessEvent(string id, string evt, params object[] data)
{
Dictionary<string, Handler> handlersForType;
if (handlers.TryGetValue(evt, out handlersForType))
{
Handler handler;
if (handlersForType.TryGetValue(id, out handler))
{
var e = new Event { Type = evt, Id = id };
if (data != null && data.Length > 0) e.Data = data;
handler(e);
}
// invoke handlers that don't care about a particular id
if (id != string.Empty && handlersForType.TryGetValue(string.Empty, out handler))
{
var e = new Event { Type = evt, Id = id };
if (data != null && data.Length > 0) e.Data = data;
handler(e);
}
}
}
static string EnumValueToString(Enum value)
{
return string.Format("{0}.{1}", value.GetType(), value);
}
}