1 /**
2 * Module for event observation.
3 *
4 * Authors:
5 *   Jacob Jensen
6 * License:
7 *   https://github.com/PoisonEngine/poison-ui/blob/master/LICENSE
8 */
9 module poison.core.eventobserver;
10 
11 import poison.core.eventhandler;
12 import poison.core.eventargs;
13 
14 /// An observer for events.
15 class EventObserver {
16   private:
17   /// Global event handlers.
18   static IBaseEventHandler[][string] _globalEventHandlers;
19 
20   /// Event handlers.
21   IBaseEventHandler[][string] _eventHandlers;
22 
23   public:
24   /**
25   * Subscribes an event handler to an event.
26   * Params:
27   *   eventName = The event to subscribe to.
28   *   handler =   The event handler.
29   */
30   void subscribe(TEventArgs : EventArgs)(string eventName, EventHandler!TEventArgs handler) {
31     _eventHandlers[eventName] ~= handler;
32   }
33 
34   /**
35   * Unsubscribes an event.
36   * Params:
37   *   eventName = The name of the event to unsubscribe.
38   */
39   void unsubscribe(string eventName) {
40     assert(eventName in _eventHandlers);
41 
42     _eventHandlers.remove(eventName);
43   }
44 
45   /**
46   * Fires an event.
47   * Params:
48   *   eventName = The name of the event to fire.
49   *   eventArgs = The event args to pass.
50   */
51   void fireEvent(TEventArgs : EventArgs)(string eventName, TEventArgs eventArgs) {
52     auto handlers = _eventHandlers.get(eventName, null);
53 
54     if (handlers) {
55       foreach (handler; handlers) {
56         (cast(EventHandler!TEventArgs)handler)(eventArgs);
57       }
58     }
59   }
60 
61   static:
62   /**
63   * Subscribes a global event handler to an event.
64   * Params:
65   *   eventName = The event to subscribe to.
66   *   handler =   The event handler.
67   */
68   void subscribeGlobal(TEventArgs : EventArgs)(string eventName, EventHandler!TEventArgs handler) {
69     _globalEventHandlers[eventName] ~= handler;
70   }
71 
72   /**
73   * Unsubscribes a global event.
74   * Params:
75   *   eventName = The name of the event to unsubscribe.
76   */
77   void unsubscribeGlobal(string eventName) {
78     assert(eventName in _globalEventHandlers);
79 
80     _globalEventHandlers.remove(eventName);
81   }
82 
83   /**
84   * Fires a global event.
85   * Params:
86   *   eventName = The name of the event to fire.
87   *   eventArgs = The event args to pass.
88   */
89   void fireEventGlobal(TEventArgs : EventArgs)(string eventName, TEventArgs eventArgs) {
90     auto handlers = _globalEventHandlers.get(eventName, null);
91 
92     if (handlers) {
93       foreach (handler; handlers) {
94         (cast(EventHandler!TEventArgs)handler)(eventArgs);
95       }
96     }
97   }
98 }