Initial commit

This commit is contained in:
2026-01-24 16:10:02 -05:00
parent e053f094b3
commit cf4020fa08
10 changed files with 267 additions and 0 deletions

55
Event.h Normal file
View File

@@ -0,0 +1,55 @@
//
// An event/listener system.
//
#ifndef EVENT_H
#define EVENT_H
#include <functional>
#include <unordered_map>
class Event;
class CallbackHandle {
public:
CallbackHandle(Event *evt, int id) : m_evt(evt), m_id(id) {
}
~CallbackHandle();
private:
Event *m_evt;
int m_id;
};
class Event {
public:
using Callback = std::function<void()>;
CallbackHandle addListener(Callback cb) {
int id = m_nextId++;
m_callbacks[id] = std::move(cb);
return CallbackHandle(this, id);
}
void remove(int id) {
m_callbacks.erase(id);
}
void fire() {
for (auto &kv : m_callbacks)
kv.second();
}
private:
friend class CallbackHandle;
std::unordered_map<int, Callback> m_callbacks;
int m_nextId = 0;
};
CallbackHandle::~CallbackHandle() {
if (m_evt)
m_evt->remove(m_id);
}
#endif // EVENT_H