-
Notifications
You must be signed in to change notification settings - Fork 72
/
class_WSEventEmitter.ahk
116 lines (103 loc) · 2.52 KB
/
class_WSEventEmitter.ahk
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
class Event
{
__new(ByRef emitter, ByRef data)
{
this.target := emitter
this.data := data
this.propagate := True
}
stopPropagation()
{
this.propagate := False
}
}
class EventEmitter
{
events := {}
_addListener(eventName, ByRef listener, atStart := 0, once := 0)
{
if(!this.events[eventName])
{
this.events[eventName] := []
}
if(atStart)
{
this.events[eventName].InsertAt(1, {listener: listener, once: once})
}
else
{
this.events[eventName].Push({listener: listener, once: once})
}
return this
}
removeListener(event, ByRef listener)
{
if(this.events[event])
{
if(listener)
{
For i, eventListener in this.events[event]
{
if(eventListener.listener == listener)
{
this.events[event].RemoveAt(i)
}
}
}
}
else
{
iListeners := this.events[eventName].Length()
this.events[eventName].RemoveAt(1, iListeners-1)
}
}
emit(eventName,ByRef data)
{
if(this.events[eventName])
{
iListeners := this.events[eventName].Length()
if(iListeners)
{
e := new Event(this, data)
For i, eventListener in this.events[eventName]
{
eventListener.listener.Call(e)
if(eventListener.once)
{
this.events[eventName].RemoveAt(i)
}
if(!e.propagate)
{
break
}
}
}
return iListeners
}
return 0
}
prependOnceListener(event, ByRef listener)
{
return this._addListener(event, listener, 1, 1)
}
prependListener(event, ByRef listener)
{
return this._addListener(event, listener, 1, 0)
}
addListener(event, ByRef listener)
{
return this._addListener(event, listener, 0, 0)
}
once(event, ByRef listener)
{
return this._addListener(event, listener, 0, 1)
}
on(event, ByRef listener)
{
return this.addListener(event, listener)
}
off(event, ByRef listener)
{
this.removeListener(event, listener)
}
}