Skip to content

Sven-vh/event-system

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

event-system

Simple single header, yet scalable, event system

This system allows you to create custom events and implement listeners across your whole codebase.

How to use

  1. Download the EventSystem.hpp file.
  2. Include it in your project.
  3. Include the EventSystem.hpp file in a header where you want to define your events and listeners.
  4. See the example below for how to create an event and a listener.

Example

Creating an event

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); }
};

Listening to an 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;
    }
};

Dispatching an event

class InputSystem {
   public:
    void update() {
        // Simulate mouse move event
        MouseMoveEvent event(100, 200);
        IMouseMoveListener::dispatch(event); // Dispatch the event to all listeners
    }
};

About

Simple single header event system

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages