-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEventBus.cpp
More file actions
53 lines (49 loc) · 1.54 KB
/
Copy pathEventBus.cpp
File metadata and controls
53 lines (49 loc) · 1.54 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
#include "EventBus.h"
#include "IEvent.h"
#include "EventSubscriber.h"
#include <algorithm>
namespace sh::core
{
EventBus::~EventBus()
{
for (auto& [hash, subscribers] : listeners)
{
for (auto& subscriber : subscribers)
{
subscriber->eventBus = nullptr;
}
}
}
SH_CORE_API void EventBus::Subscribe(ISubscriber& subscriber)
{
subscriber.eventBus = this;
const auto eventTypeHash = subscriber.GetEventTypeHash();
listeners[eventTypeHash].push_back(&subscriber);
}
SH_CORE_API void EventBus::Unsubscribe(ISubscriber& subscriber)
{
const auto eventTypeHash = subscriber.GetEventTypeHash();
auto it = listeners.find(eventTypeHash);
if (it == listeners.end())
return;
auto& subscribers = it->second;
auto removeIt = std::remove(subscribers.begin(), subscribers.end(), &subscriber);
if (removeIt == subscribers.end())
return;
subscriber.eventBus = nullptr;
subscribers.erase(removeIt, subscribers.end());
}
SH_CORE_API void EventBus::Publish(const IEvent& event)
{
const auto eventTypeHash = event.GetTypeHash();
auto it = listeners.find(eventTypeHash);
if (it == listeners.end())
return;
std::vector<ISubscriber*> subscribersCopy = it->second;
for (auto* subscriber : subscribersCopy)
{
if (subscriber->eventBus)
subscriber->Invoke(event);
}
}
}