#include <functional>
#include <vector>
+#include <msp/core/noncopyable.h>
namespace Msp::Game {
{ 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 *);
std::vector<Dispatcher> dispatchers;
+public:
+ ~EventBus();
+
+private:
static unsigned get_next_id();
public:
template<typename T>
void dispatch(const T &) const;
+
+ template<typename T>
+ void dispatch_to(EventObserver &, const T &) 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()
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