44 lines
980 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);
}
}
2021-04-19 19:46:03 +02:00
void bindHandler(const EventHandler<T>& handler) {
2020-11-12 00:53:38 +01:00
handlers.push_back(handler);
}
2021-04-19 19:46:03 +02:00
void unbindHandler(const EventHandler<T>& handler) {
2020-11-12 00:53:38 +01:00
if (handlers.find(handler) == handlers.end()) {
spdlog::error("Tried to remove a non-existant event handler");
return;
}
handlers.erase(std::remove(handlers.begin(), handlers.end(), handler), handlers.end());
}
private:
2021-04-19 19:46:03 +02:00
std::vector<EventHandler<T>> handlers;
2020-11-12 00:53:38 +01:00
};