1
+ 'use strict'
2
+
3
+ function eventManager ( ) {
4
+ this . registered = { }
5
+ this . anonymous = { }
6
+ }
7
+
8
+ /*
9
+ * Unregister a listener.
10
+ * Note that if obj is a function. the unregistration will be applied to the dummy obj {}.
11
+ *
12
+ * @param {String } eventName - the event name
13
+ * @param {Object or Func } obj - object that will listen on this event
14
+ * @param {Func } func - function of the listeners that will be executed
15
+ */
16
+ eventManager . prototype . unregister = function ( eventName , obj , func ) {
17
+ if ( ! this . registered [ eventName ] ) {
18
+ return
19
+ }
20
+ if ( obj instanceof Function ) {
21
+ func = obj
22
+ obj = this . anonymous
23
+ }
24
+ for ( let reg in this . registered [ eventName ] ) {
25
+ if ( this . registered [ eventName ] [ reg ] . obj === obj && this . registered [ eventName ] [ reg ] . func === func ) {
26
+ this . registered [ eventName ] . splice ( reg , 1 )
27
+ }
28
+ }
29
+ }
30
+
31
+ /*
32
+ * Register a new listener.
33
+ * Note that if obj is a function, the function registration will be associated with the dummy object {}
34
+ *
35
+ * @param {String } eventName - the event name
36
+ * @param {Object or Func } obj - object that will listen on this event
37
+ * @param {Func } func - function of the listeners that will be executed
38
+ */
39
+ eventManager . prototype . register = function ( eventName , obj , func ) {
40
+ if ( ! this . registered [ eventName ] ) {
41
+ this . registered [ eventName ] = [ ]
42
+ }
43
+ if ( obj instanceof Function ) {
44
+ func = obj
45
+ obj = this . anonymous
46
+ }
47
+ this . registered [ eventName ] . push ( {
48
+ obj : obj ,
49
+ func : func
50
+ } )
51
+ }
52
+
53
+ /*
54
+ * trigger event.
55
+ * Every listener have their associated function executed
56
+ *
57
+ * @param {String } eventName - the event name
58
+ * @param {Array }j - argument that will be passed to the executed function.
59
+ */
60
+ eventManager . prototype . trigger = function ( eventName , args ) {
61
+ if ( ! this . registered [ eventName ] ) {
62
+ return
63
+ }
64
+ for ( let listener in this . registered [ eventName ] ) {
65
+ const l = this . registered [ eventName ] [ listener ]
66
+ l . func . apply ( l . obj === this . anonymous ? { } : l . obj , args )
67
+ }
68
+ }
69
+
70
+ module . exports = eventManager
0 commit comments