X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Fgame%2Feventbus.h;h=b9e6c7890c77f5a56cb83f83cfd20c95c08a57c3;hb=e3b8bcdcb5abfdc4cfaf0af0f9633ac15d1f3b69;hp=e09663589c8c99fe02180db76b94fbe6506af54b;hpb=9248910baf5bab301c7329182b143870321a95f0;p=libs%2Fgame.git diff --git a/source/game/eventbus.h b/source/game/eventbus.h index e096635..b9e6c78 100644 --- a/source/game/eventbus.h +++ b/source/game/eventbus.h @@ -3,6 +3,7 @@ #include #include +#include namespace Msp::Game { @@ -23,13 +24,14 @@ struct EventDispatcher { handlers.emplace_back(obs, std::move(cb)); } void remove_observer(EventObserver *obs) - { std::erase_if(handlers, [obs](const Handler &h){ return h.observer==obs; }); } + { std::erase_if(handlers, [obs](auto &h){ return h.observer==obs; }); } void dispatch(const T &) const; + void dispatch_to(EventObserver &, const T &) const; }; -class EventBus +class EventBus: public NonCopyable { private: using DeleteFunc = void(void *); @@ -44,6 +46,10 @@ private: std::vector dispatchers; +public: + ~EventBus(); + +private: static unsigned get_next_id(); public: @@ -52,18 +58,21 @@ public: private: template - EventDispatcher &get_emitter(); + EventDispatcher &get_dispatcher(); public: template void add_observer(EventObserver &obs, std::function cb) - { get_emitter().add_observer(&obs, std::move(cb)); } + { get_dispatcher().add_observer(&obs, std::move(cb)); } void replace_observer(EventObserver &, EventObserver &); void remove_observer(EventObserver &); template void dispatch(const T &) const; + + template + void dispatch_to(EventObserver &, const T &) const; }; @@ -74,6 +83,14 @@ void EventDispatcher::dispatch(const T &event) const h.callback(event); } +template +void EventDispatcher::dispatch_to(EventObserver &obs, const T &event) const +{ + for(const Handler &h: handlers) + if(h.observer==&obs) + h.callback(event); +} + template inline unsigned EventBus::get_event_id() @@ -83,7 +100,7 @@ inline unsigned EventBus::get_event_id() } template -inline EventDispatcher &EventBus::get_emitter() +inline EventDispatcher &EventBus::get_dispatcher() { unsigned id = get_event_id(); if(dispatchers.size()<=id) @@ -108,6 +125,14 @@ inline void EventBus::dispatch(const T &event) const static_cast *>(dispatchers[id].dispatcher)->dispatch(event); } +template +inline void EventBus::dispatch_to(EventObserver &obs, const T &event) const +{ + unsigned id = get_event_id(); + if(id *>(dispatchers[id].dispatcher)->dispatch_to(obs, event); +} + } // namespace Msp::Game #endif