44 lines
1001 B
C
Raw Normal View History

2020-11-12 00:53:38 +01:00
#pragma once
#include <vector>
#include <spdlog/spdlog.h>
2021-04-19 19:46:03 +02:00
template <class T>
struct EventHandler {
EventHandler() {}
EventHandler(void (*handler)(T, void*), void* ctx) {
this->handler = handler;
this->ctx = ctx;
}
void (*handler)(T, void*);
void* ctx;
};
2020-11-12 00:53:38 +01:00
template <class T>
class Event {
public:
Event() {}
~Event() {}
void emit(T value) {
for (auto const& handler : handlers) {
handler->handler(value, handler->ctx);
2020-11-12 00:53:38 +01:00
}
}
void bindHandler(EventHandler<T>* handler) {
2020-11-12 00:53:38 +01:00
handlers.push_back(handler);
}
void unbindHandler(EventHandler<T>* handler) {
if (std::find(handlers.begin(), handlers.end(), handler) == handlers.end()) {
2020-11-12 00:53:38 +01:00
spdlog::error("Tried to remove a non-existant event handler");
return;
}
handlers.erase(std::remove(handlers.begin(), handlers.end(), handler), handlers.end());
}
private:
std::vector<EventHandler<T>*> handlers;
2020-11-12 00:53:38 +01:00
};