-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventManager.js
81 lines (74 loc) · 2.32 KB
/
EventManager.js
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
class EventManager {
constructor(isSingleton) {
console.log("EventManager: starting");
// Collection of {event, [subscribedCallbacks]}
this.subscriptions = []
// if isSingleton is true, the object is attached to the document (only once)
if(isSingleton){
if(window.eventManager === undefined){
console.log("EventManager: creating singleton");
window.eventManager = this
}
else{
console.log("EventManager: already instantiated");
}
}
else{
console.log("EventManager: is not a singleton");
}
}
subscribe(eventToSubscribe, callback){
var eventObject = this.isCallbackSubscribed(eventToSubscribe, callback)
if(eventObject === undefined){
var eventFound = false
this.subscriptions.forEach(function(e){
if(e._event === eventToSubscribe){
eventFound = true
e.subscribedCallbacks.push(callback)
}
})
if(!eventFound){
var subscribedCallbacks = [callback]
this.subscriptions.push({_event: eventToSubscribe, subscribedCallbacks: subscribedCallbacks})
}
}
else{
console.log("EventManager: callback already subscribed to event " + eventToSubscribe);
}
}
unsubscribe(eventToUnubscribe, callback){
var eventObj = this.isCallbackSubscribed(eventToUnubscribe, callback);
if(eventObj!==undefined)
{
this.subscriptions[eventObj.eventIndex].subscribedCallbacks.pop(eventObj.callbackIndex)
}
console.log("EventManager: callback unsubscribed from " + eventToUnubscribe);
}
isCallbackSubscribed(event, callback){
var result = undefined
this.subscriptions.forEach(function(e, i){
if(e._event === event){
e.subscribedCallbacks.forEach(function(c, j){
if(c.toString() === callback.toString()){
result = {eventIndex:i, callbackIndex:j }
}
})
}
})
return result
}
dispatch(eventToDispatch, payload){
console.log("EventManager: dispatching");
console.log({_event: eventToDispatch, payload: payload});
this.subscriptions.forEach(function(e){
if(e._event === eventToDispatch){
e.subscribedCallbacks.forEach(function(c){
c(payload)
})
}
})
}
showAllSubsriptions(){
console.log($.extend(true, {}, this.subscriptions));
}
}