mirror of
https://github.com/jslightham/cpp-utils.git
synced 2026-03-09 18:12:26 +01:00
Initial commit
This commit is contained in:
55
Event.h
Normal file
55
Event.h
Normal 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
|
||||
Reference in New Issue
Block a user