Skip to content

Event listeners should be lambda friendly #236

Description

@bradphelan

Currently it's not possible to pass lambdas as event listeners

void EventDispatcher::addEventListener(const std::string& type, EventListener* listener) 

You enforce a virtual base type and also force to pass by pointer. Both of these make it impossible to use lambdas. This makes the code much more noisy forcing users to create classes instead of simple callbacks. Instead of a base class

    struct EventListener {

        virtual void onEvent(Event& event) = 0;

        virtual ~EventListener() = default;
    };

It would be better simply to define

    using EventListener = std::function<void(Event&event)>;

and pass and store the callback by value. The problem then becomes how to remove the event. Easy is to use a std::shared_ptr with and return it. So we end up with

    std::shared_ptr<EventListenerHandle> addEventListener(std::function<void(Event&event)>);

The user then hangs onto the EventListenerHandle till they don't need it anymore. As soon as the last copy of this goes out of scope then the listener will be removed. I know you want to make this like threejs but c++ is different and you should take advantage of RAII lifetimes and lambdas.

appModel.listenerSubscription =  mesh.addEventListener(
    [](Event & event){ std::cout << "my mesh was clicked" << std::endl; }
);

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions