-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.hxx
114 lines (86 loc) · 2.41 KB
/
index.hxx
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
#ifndef __EVENTS_H_
#define __EVENTS_H_
#include <iostream>
#include <stdexcept>
#include <functional>
#include <typeinfo>
#include <string>
#include <map>
class EventEmitter {
std::map<std::string, void*> events;
std::map<std::string, bool> events_once;
template <typename Callback>
struct traits : public traits<decltype(&Callback::operator())> {
};
template <typename ClassType, typename R, typename... Args>
struct traits<R(ClassType::*)(Args...) const> {
typedef std::function<R(Args...)> fn;
};
template <typename Callback>
typename traits<Callback>::fn
to_function (Callback& cb) {
return static_cast<typename traits<Callback>::fn>(cb);
}
int _listeners = 0;
public:
int maxListeners = 10;
int listeners() {
return this->_listeners;
}
template <typename Callback>
void on(const std::string& name, Callback cb) {
auto it = events.find(name);
if (it != events.end()) {
throw new std::runtime_error("duplicate listener");
}
if (++this->_listeners >= this->maxListeners) {
std::cout
<< "warning: possible EventEmitter memory leak detected. "
<< this->_listeners
<< " listeners added. "
<< std::endl;
};
auto f = to_function(cb);
auto fn = new decltype(f)(to_function(cb));
events[name] = static_cast<void*>(fn);
}
template <typename Callback>
void once(const std::string& name, Callback cb) {
this->on(name, cb);
events_once[name] = true;
}
void off() {
events.clear();
events_once.clear();
this->_listeners = 0;
}
void off(const std::string& name) {
auto it = events.find(name);
if (it != events.end()) {
events.erase(it);
this->_listeners--;
auto once = events_once.find(name);
if (once != events_once.end()) {
events_once.erase(once);
}
}
}
template <typename ...Args>
void emit(std::string name, Args... args) {
auto it = events.find(name);
if (it != events.end()) {
auto cb = events.at(name);
auto fp = static_cast<std::function<void(Args...)>*>(cb);
(*fp)(args...);
}
auto once = events_once.find(name);
if (once != events_once.end()) {
this->off(name);
}
}
EventEmitter(void) {}
~EventEmitter (void) {
events.clear();
}
};
#endif