6#include <Utility/TFunction.h>
7#include <Common/primitive_type.h>
8#include <Common/assertion.h>
9#include <Common/exceptions.h>
10#include <Utility/TUniquePtrVector.h>
21template<
typename EventType>
24 static_assert(std::is_base_of_v<Event, EventType>);
55 template<
typename DispatchFunc>
56 void dispatch(
const EventType& e, DispatchFunc dispatchFunc);
61 TUniquePtrVector<Listener> m_listeners;
62 std::vector<Listener*> m_listenersToRemove;
63 bool m_isDispatching =
false;
66template<
typename EventType>
70 return m_listeners.add(std::make_unique<Listener>(std::move(listener)));
73template<
typename EventType>
82 m_listenersToRemove.push_back(listener);
85template<
typename EventType>
95 throw IllegalOperationException(
96 "Cannot remove listeners during dispatch. Use removeListener(1) instead.");
99 const auto removedListener = m_listeners.remove(listener);
100 PH_ASSERT(removedListener !=
nullptr);
103template<
typename EventType>
104template<
typename DispatchFunc>
107 static_assert(std::is_invocable_v<DispatchFunc, EventType, Listener>,
108 "DispatchFunc must take (EventType, Listener).");
113 for(
Listener* listener : m_listenersToRemove)
115 removeListenerImmediately(listener);
117 m_listenersToRemove.clear();
125 const auto numListeners = m_listeners.size();
128 PH_ASSERT(!m_isDispatching);
130 m_isDispatching =
true;
131 for(std::size_t listenerIdx = 0; listenerIdx < numListeners; ++listenerIdx)
133 dispatchFunc(e, *m_listeners[listenerIdx]);
135 m_isDispatching =
false;
138template<
typename EventType>
143 [](
const EventType& e,
const Listener& listener)
Definition TEventDispatcher.h:23
void removeListener(Listener *listener)
Remove a listener that was added to this dispatcher. The listener will not be removed immediately....
Definition TEventDispatcher.h:74
void dispatch(const EventType &e)
Definition TEventDispatcher.h:139
TEventListener< EventType > Listener
Definition TEventDispatcher.h:27
void removeListenerImmediately(Listener *listener)
Immediately remove a listener that was added to this dispatcher.
Definition TEventDispatcher.h:86
Listener * addListener(Listener listener)
Definition TEventDispatcher.h:67
void dispatch(const EventType &e, DispatchFunc dispatchFunc)
Submit an event to the listeners.
Definition TEventDispatcher.h:105
Definition ph_editor.h:10
TFunction< void(const EventType &e)> TEventListener
Definition TEventListener.h:9