1 #ifndef MSP_GAME_EVENTSOURCE_H_
2 #define MSP_GAME_EVENTSOURCE_H_
5 #include "eventobserver.h"
17 EventSourceBase(EventBus &b): bus(b) { }
19 virtual void remove_observer(EventObserver &) = 0;
23 template<typename... E>
24 class EventSource: public EventSourceBase, private EventDispatcher<E>...
27 EventSource(EventBus &b): EventSourceBase(b) { }
28 ~EventSource() { (cancel_observation<E>(), ...); }
31 void add_observer(EventObserver &obs, std::function<void(const T &)> cb)
32 { static_cast<EventDispatcher<T> &>(*this).add_observer(&obs, std::move(cb)); }
34 void remove_observer(EventObserver &obs) override
35 { (static_cast<EventDispatcher<E> &>(*this).remove_observer(&obs), ...); }
39 void cancel_observation();
42 template<typename T, typename... Args>
43 void emit(Args &&...) const;
45 template<typename T, typename... Args>
46 void emit_to(EventObserver &, Args &&...) const;
50 template<typename... E>
52 inline void EventSource<E...>::cancel_observation()
54 for(const auto &h: static_cast<EventDispatcher<T> &>(*this).handlers)
55 h.observer->remove_source(*this);
58 template<typename... E>
59 template<typename T, typename... Args>
60 inline void EventSource<E...>::emit(Args &&... args) const
62 T event(std::forward<Args>(args)...);
63 static_cast<const EventDispatcher<T> &>(*this).dispatch(event);
67 template<typename... E>
68 template<typename T, typename... Args>
69 inline void EventSource<E...>::emit_to(EventObserver &obs, Args &&... args) const
71 T event(std::forward<Args>(args)...);
72 static_cast<const EventDispatcher<T> &>(*this).dispatch_to(obs, event);
73 bus.dispatch_to(obs, event);
76 } // namespace Msp::Game