RedCore
Loading...
Searching...
No Matches
EventDelegator.h
Go to the documentation of this file.
1#pragma once
2
3#include <container/seadTList.h>
4#include <telkin/Print.h>
5
6namespace red {
7
8 template <typename T> //requires std::derived_from<T, EventBase>
10 public:
11 using Callback = void (*)(T& event);
12
13 public:
14 class Listener {
15 public:
16 // higher priority = fires earlier
17 Listener(Callback callback, s32 priority)
18 : mNode(this)
19 , mCallback(callback)
21 { }
22
24 void invoke(T& event) const {
25 return mCallback(event);
26 }
27
28 [[nodiscard]]
29 sead::TListNode<Listener*>& getNode() { return mNode; }
30
31 [[nodiscard]]
32 s32 getPriority() const { return mPriority; }
33
34 private:
35 sead::TListNode<Listener*> mNode;
36 Callback mCallback;
37 s32 mPriority;
38 };
39
40 public:
41 void connect(Listener& listener) {
42 mListeners.pushBack(&listener.getNode());
43 mListeners.sort(&compare);
44 }
45
46 void fire(T& event) const {
47 for (const Listener* listener : mListeners) {
48 listener->invoke(event);
49
50 if (event.isConsumed()) [[unlikely]]
51 return; // stop propagation
52 }
53 }
54
55 private:
56 static s32 compare(Listener* const* a, Listener* const* b) {
57 if ((*a)->getPriority() < (*b)->getPriority())
58 return 1;
59
60 if ((*b)->getPriority() < (*a)->getPriority())
61 return -1;
62
63 return 0;
64 }
65
66 private:
67 sead::TList<Listener*> mListeners;
68 };
69
70}
Definition EventDelegator.h:14
Listener(Callback callback, s32 priority)
Definition EventDelegator.h:17
sead::TListNode< Listener * > & getNode()
Definition EventDelegator.h:29
s32 getPriority() const
Definition EventDelegator.h:32
void invoke(T &event) const
Definition EventDelegator.h:24
Definition EventDelegator.h:9
void fire(T &event) const
Definition EventDelegator.h:46
void connect(Listener &listener)
Definition EventDelegator.h:41
void(*)(T &event) Callback
Definition EventDelegator.h:11
Definition ActorDonutBlock.h:5