Simple single header, yet scalable, event system
This system allows you to create custom events and implement listeners across your whole codebase.
- Download the
EventSystem.hppfile. - Include it in your project.
- Include the
EventSystem.hppfile in a header where you want to define your events and listeners. - See the example below for how to create an event and a listener.
To create an event, you need to define a class that inherits from EventBase. You can add any data members you want to pass with the event.
Additionally, you need to create a listener interface that inherits from EventListenerBase. With as template parameter the class and the event type.
class MouseMoveEvent : public EventBase {
public:
MouseMoveEvent(float x, float y) : x(x), y(y) {}
const float x = 0, y = 0;
};
class IMouseMoveListener : public EventListenerBase<IMouseMoveListener, MouseMoveEvent> {
public:
IMouseMoveListener() { listeners.push_back(this); }
virtual void on_mouse_move(MouseMoveEvent& event) = 0;
void on_event(MouseMoveEvent& event) final override { on_mouse_move(event); }
};class MyGame : public IMouseMoveListener {
public:
MyGame() { priority = 1; } // Set priority for this listener, higher number = higher priority
void on_mouse_move(MouseMoveEvent& event) override {
// Do something with the event
std::cout << "Mouse moved to: " << event.x << ", " << event.y << std::endl;
//optionally mark the event as handled, so it won't be dispatched to other listeners
event.handled = true;
}
};class InputSystem {
public:
void update() {
// Simulate mouse move event
MouseMoveEvent event(100, 200);
IMouseMoveListener::dispatch(event); // Dispatch the event to all listeners
}
};