I wrote a simple concept of an event system in cpp. It is uses a namespace and a global state, but normally a global state with namespaces is bad practice.
Is there a better way to do simple event handling with multiple callback functions?
header:
#ifndef EVENTS_EVENTMANAGER_H
#define EVENTS_EVENTMANAGER_H
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <vector>
#include <functional>
namespace eventmanager
{
//resize event
static std::vector<std::function<void(GLFWwindow*, int, int)>> resizeEventCallbacks;
void resizeEvent(GLFWwindow *window, int width, int hight);
void subscribeResize(std::function<void(GLFWwindow*, int, int)> callback);
}
#endif //EVENTS_EVENTMANAGER_H
cpp:
#include "events/eventmanager.h"
void eventmanager::resizeEvent(GLFWwindow *window, int width, int hight)
{
for (auto &callback: eventmanager::resizeEventCallbacks)
{
callback(window, width, hight);
}
}
void eventmanager::subscribeResize(std::function<void(GLFWwindow *, int, int)> callback)
{
eventmanager::resizeEventCallbacks.push_back(callback);
}
usage:
eventmanager::subscribeResize([&](GLFWwindow *window, int width, int hight) {
...
});