-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_store.js
More file actions
105 lines (97 loc) · 3.15 KB
/
event_store.js
File metadata and controls
105 lines (97 loc) · 3.15 KB
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
import {each, remove} from 'lodash';
export default class EventStore {
constructor() {
this.store = new Map();
this.onceStore = new Map();
}
/**
* Создает хранитель события
* @param {string} name - имя события
* @return {EventStore} cbs - колбеки которые будут вызваны при резолве события
* */
createStore(name, cbs = []) {
if(!this.store.has(name)) {
this.store.set(name, cbs.slice());
}
if(!this.onceStore.has(name)) {
this.onceStore.set(name, cbs.slice());
}
return this;
}
once(name, cb) {
if(name) {
var cbs = [];
if(!this.onceStore.has(name)) {
this.onceStore.set(name, cbs);
} else {
cbs = this.onceStore.get(name);
}
cbs.push(cb);
}
return this;
}
on(name, cb) {
this.addEvent(name,cb);
}
/**
* Добавляем событие в массив реакции на событие
* P.S Важно помнить что функции буду вызваны без контекста,
* так что нельзя использовать this внутри контекста обработчика события
* @param {string} name - имя события
* @param {Function} cb - функция вызываемая при возникновени события
* @return {EventStore} текущий контекст
* */
addEvent(name, cb) {
if(name) {
var cbs = [];
if(!this.store.has(name)) {
this.store.set(name, cbs);
} else {
cbs = this.store.get(name);
}
cbs.push(cb);
}
return this;
}
/**
* Вызывает событие при наступление события
* @param {string} name - имя события
* @param {*} args - аргументы с которыми будут вызваны фунции
* @return {EventStore} текущий контекст
* */
resolve(name, ...args) {
if(name ) {
if(this.store.has(name)) {
_.each(this.store.get(name), function(cb) {
cb.apply(null, args);
});
}
if(this.onceStore.has(name)) {
_.each(this.onceStore.get(name), function(cb) {
cb.apply(null, args);
});
this.onceStore.set(name, []);
}
}
return this;
}
remove(name, cb) {
if(this.store.has(name)) {
remove(this.store.get(name), (cbEvent) => {
return cbEvent === cb;
})
}
if(this.onceStore.has(name)) {
remove(this.onceStore.get(name), (cbEvent) => {
return cbEvent === cb;
})
}
}
/**
* Удаляет все события и события
* @return {undefined}
* */
destroy() {
this.store.clear();
}
}