-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventController.h
More file actions
64 lines (47 loc) · 1.98 KB
/
EventController.h
File metadata and controls
64 lines (47 loc) · 1.98 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
#ifndef EVENT_CONTROLLER_H
#define EVENT_CONTROLLER_H
#include <functional>
#include <unordered_map>
#include <vector>
#include <typeindex>
#include <string>
class EventController {
private:
using CallbackID = size_t;
using EventCallbackList = std::vector<std::pair<CallbackID, std::function<void(const void*)>>>;
std::unordered_map<std::type_index, EventCallbackList> subscriptions;
CallbackID nextCallbackID = 0;
public:
template <typename EventType>
CallbackID Subscribe(std::function<void(const EventType&)> callback) {
auto wrapper = [callback](const void* eventData) {
callback(*static_cast<const EventType*>(eventData));
};
CallbackID currentId = nextCallbackID++;
subscriptions[typeid(EventType)].push_back(std::make_pair(currentId, wrapper));
return currentId;
}
template <typename EventType>
void Unsubscribe(CallbackID callbackId) {
auto eventTypeIterator = subscriptions.find(typeid(EventType));
if (eventTypeIterator == subscriptions.end()) return;
auto& callbackList = eventTypeIterator->second;
auto callbackIterator = std::find_if(callbackList.begin(), callbackList.end(),
[callbackId](const auto& subscription) {
return subscription.first == callbackId;
});
if (callbackIterator != callbackList.end()) {
callbackList.erase(callbackIterator);
}
}
template <typename EventType>
void Emit(const EventType& event) {
auto eventTypeIterator = subscriptions.find(typeid(EventType));
if (eventTypeIterator == subscriptions.end()) return;
for (const auto& callbackPair : eventTypeIterator->second) {
auto callback = callbackPair.second;
callback(&event);
}
}
};
#endif