Skip to content

Suggested Rewrite for Event Dispatcher Section #1299

@MrDrElliot

Description

@MrDrElliot

Hello,

https://github.com/skypjack/entt/wiki/Events,-signals-and-everything-in-between#event-dispatcher
The documentation states that listeners must be types "that offer one or more member functions," which is misleading since the dispatcher actually accepts both free functions and member functions.

They also accept lambdas under certain conditions,so it might also be beneficial to add some examples of those as well.

Proposed Revision:


Event dispatcher

The event dispatcher class allows users to trigger immediate events or to queue and publish them all together later.

This class lazily instantiates its queues. Therefore, it is not necessary to announce the event types in advance:

// define a general purpose dispatcher
entt::dispatcher dispatcher{};

Connecting Listeners

Listeners can be connected to a dispatcher in two ways:

  1. Free functions - Functions that accept an event reference as their parameter
  2. Member functions - Methods of class instances that accept an event reference

These listeners are connected via the connect member function on a sink:

struct an_event { int value; };
struct another_event {};

// Free function listener
void on_event(const an_event &event) { /* ... */ }

// Class-based listener
struct listener {
    void receive(const an_event &) { /* ... */ }
    void method(const another_event &) { /* ... */ }
};

// Connecting free functions
dispatcher.sink<an_event>().connect<&on_event>();

// Connecting lambdas
dispatcher.sink<an_event>().connect<[](an_event& e) {}>();

// Connecting member functions
listener instance;
dispatcher.sink<an_event>().connect<&listener::receive>(instance);
dispatcher.sink<another_event>().connect<&listener::method>(instance);

Listeners must be callable with an argument of type Event & (or const Event &) for the specific event type, regardless of the return value.

Note: Connecting listeners within event handlers can result in undefined behavior.

Disconnecting Listeners

The disconnect member function is used to remove one listener at a time or all of them at once:

// Disconnect a specific free function
dispatcher.sink<an_event>().disconnect<&on_event>();

// Disconnect a specific member function
dispatcher.sink<an_event>().disconnect<&listener::receive>(instance);

// Disconnecting lambdas
dispatcher.sink<an_event>().disconnect<[](an_event& e) {}>();

// Disconnect all listeners from a specific instance
dispatcher.sink<another_event>().disconnect(&instance);

Metadata

Metadata

Assignees

Labels

documentationdocs related issues/requests

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions