-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEventDispatcher.h
More file actions
62 lines (47 loc) · 1.18 KB
/
EventDispatcher.h
File metadata and controls
62 lines (47 loc) · 1.18 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
/**
* @Author Sagi Zeevi
* @see https://gist.github.com/sagi-z/f8b734a2240ce203ba5b2977e54b4414#file-dispatcher-hpp
*/
#ifndef EVENTDISPATCHER_H
#define EVENTDISPATCHER_H
#include <functional>
#include <list>
template <typename... Args>
class EventDispatcher {
public:
typedef std::function<void(Args...) > CallBackFunction;
class CBID {
public:
CBID() : valid(false) {
}
private:
friend class EventDispatcher<Args...>;
CBID(typename std::list<CallBackFunction>::iterator i)
: iter(i), valid(true) {
}
typename std::list<CallBackFunction>::iterator iter;
bool valid;
};
// register to be notified
CBID addCallBack(CallBackFunction cb) {
if (cb) {
cbs.push_back(cb);
return CBID(--cbs.end());
}
return CBID();
}
// unregister to be notified
void removeCallBack(CBID &id) {
if (id.valid) {
cbs.erase(id.iter);
}
}
void broadcast(Args... args) {
for (auto &cb : cbs) {
cb(args...);
}
}
private:
std::list<CallBackFunction> cbs;
};
#endif /* EVENTDISPATCHER_H */