]> git.tdb.fi Git - libs/game.git/blobdiff - source/game/eventbus.h
Provide a way to request events for existing entities and components
[libs/game.git] / source / game / eventbus.h
index 7da047ed1851b76b8bd79b6d903aa8b20c64b47e..a4de18f2bb24c699fb73aea61794b73578cdba77 100644 (file)
@@ -26,6 +26,7 @@ struct EventDispatcher
        { std::erase_if(handlers, [obs](auto &h){ return h.observer==obs; }); }
 
        void dispatch(const T &) const;
+       void dispatch_to(EventObserver &, const T &) const;
 };
 
 
@@ -64,6 +65,9 @@ public:
 
        template<typename T>
        void dispatch(const T &) const;
+
+       template<typename T>
+       void dispatch_to(EventObserver &, const T &) const;
 };
 
 
@@ -74,6 +78,14 @@ void EventDispatcher<T>::dispatch(const T &event) const
                h.callback(event);
 }
 
+template<typename T>
+void EventDispatcher<T>::dispatch_to(EventObserver &obs, const T &event) const
+{
+       for(const Handler &h: handlers)
+               if(h.observer==&obs)
+                       h.callback(event);
+}
+
 
 template<typename T>
 inline unsigned EventBus::get_event_id()
@@ -108,6 +120,14 @@ inline void EventBus::dispatch(const T &event) const
                static_cast<EventDispatcher<T> *>(dispatchers[id].dispatcher)->dispatch(event);
 }
 
+template<typename T>
+inline void EventBus::dispatch_to(EventObserver &obs, const T &event) const
+{
+       unsigned id = get_event_id<T>();
+       if(id<dispatchers.size() && dispatchers[id].dispatcher)
+               static_cast<EventDispatcher<T> *>(dispatchers[id].dispatcher)->dispatch_to(obs, event);
+}
+
 } // namespace Msp::Game
 
 #endif