-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdispatcher.js
59 lines (50 loc) · 1.15 KB
/
dispatcher.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
const Dispatcher = (function(){
function create(){
const dispatcher = {};
bind(dispatcher);
dispatcher.init();
return dispatcher;
}
function bind(dispatcher){
dispatcher.init = init.bind(dispatcher);
dispatcher.addEventListener = addEventListener.bind(dispatcher);
dispatcher.trigger = trigger.bind(dispatcher);
dispatcher.removeEventListener = removeEventListener.bind(dispatcher);
}
function addEventListener(event, callback){
const id = this.model.id++;
if(this.model.listeners[event]){
this.model.listeners[event].push({
id : id,
callback : callback
});
return id;
}else{
this.model.listeners[event] = [{
id : id,
callback : callback
}];
}
}
function trigger(event, details){
if(this.model.listeners[event]){
this.model.listeners[event].forEach(x => x.callback(details));
}
}
function removeEventListener(id){
for(let listenerList of this.model.listeners){
const index = listenerList.findIndex(x => x.id === id);
listenerList.splice(index, 1);
}
}
function init(){
this.model = {
listeners : {},
currentId : 0
};
}
return {
create,
globalDispatcher : create()
};
})();