yaze
0.3.2
Link to the Past ROM Editor
Loading...
Searching...
No Matches
event_bus.h
Go to the documentation of this file.
1
#ifndef YAZE_APP_EDITOR_CORE_EVENT_BUS_H_
2
#define YAZE_APP_EDITOR_CORE_EVENT_BUS_H_
3
4
#include <functional>
5
#include <typeindex>
6
#include <unordered_map>
7
#include <vector>
8
#include <memory>
9
#include <algorithm>
10
11
namespace
yaze
{
12
13
struct
Event
{
14
virtual
~Event
() =
default
;
15
};
16
17
class
EventBus
{
18
public
:
19
using
HandlerId
= size_t;
20
21
template
<
typename
T>
22
HandlerId
Subscribe
(std::function<
void
(
const
T&)> handler) {
23
static_assert
(std::is_base_of<Event, T>::value,
"T must derive from Event"
);
24
auto
type_idx = std::type_index(
typeid
(T));
25
auto
wrapper = [handler](
const
Event
& e) {
26
handler(
static_cast<
const
T&
>
(e));
27
};
28
29
size_t
id
=
next_id_
++;
30
handlers_
[type_idx].push_back({id, wrapper});
31
return
id;
32
}
33
34
template
<
typename
T>
35
void
Publish
(
const
T& event) {
36
static_assert
(std::is_base_of<Event, T>::value,
"T must derive from Event"
);
37
auto
type_idx = std::type_index(
typeid
(T));
38
if
(
handlers_
.find(type_idx) !=
handlers_
.end()) {
39
for
(
const
auto
& handler :
handlers_
[type_idx]) {
40
handler.fn(event);
41
}
42
}
43
}
44
45
void
Unsubscribe
(
HandlerId
id
) {
46
for
(
auto
& [type, list] :
handlers_
) {
47
auto
it = std::remove_if(list.begin(), list.end(),
48
[
id
](
const
HandlerEntry
& entry) { return entry.id == id; });
49
if
(it != list.end()) {
50
list.erase(it, list.end());
51
return
;
52
}
53
}
54
}
55
56
private
:
57
struct
HandlerEntry
{
58
HandlerId
id
;
59
std::function<void(
const
Event
&)>
fn
;
60
};
61
62
std::unordered_map<std::type_index, std::vector<HandlerEntry>>
handlers_
;
63
HandlerId
next_id_
= 1;
64
};
65
66
}
// namespace yaze
67
68
#endif
// YAZE_APP_EDITOR_CORE_EVENT_BUS_H_
yaze::EventBus
Definition
event_bus.h:17
yaze::EventBus::Publish
void Publish(const T &event)
Definition
event_bus.h:35
yaze::EventBus::Unsubscribe
void Unsubscribe(HandlerId id)
Definition
event_bus.h:45
yaze::EventBus::Subscribe
HandlerId Subscribe(std::function< void(const T &)> handler)
Definition
event_bus.h:22
yaze::EventBus::next_id_
HandlerId next_id_
Definition
event_bus.h:63
yaze::EventBus::HandlerId
size_t HandlerId
Definition
event_bus.h:19
yaze::EventBus::handlers_
std::unordered_map< std::type_index, std::vector< HandlerEntry > > handlers_
Definition
event_bus.h:62
yaze
Definition
application.cc:18
yaze::EventBus::HandlerEntry
Definition
event_bus.h:57
yaze::EventBus::HandlerEntry::id
HandlerId id
Definition
event_bus.h:58
yaze::EventBus::HandlerEntry::fn
std::function< void(const Event &) fn)
Definition
event_bus.h:59
yaze::Event
Definition
event_bus.h:13
yaze::Event::~Event
virtual ~Event()=default
src
app
editor
core
event_bus.h
Generated by
1.10.0