Class
Event
A list of listeners that are called when the event is triggered.
Introduction#
Listeners are called in the order they were added, in the coroutine that triggers the event, one at a time: a slow listener delays the trigger. A listener that throws stops the trigger: the exception reaches the caller of trigger() and the listeners after it are not called.
Class synopsis#
final class Event {
/* Methods */
public Event::trigger(mixed ...$args): void
public Event::listen(Closure ...$listeners): void
public Event::once(Closure ...$listeners): void
public Event::off(Closure ...$listeners): void
public Event::hasListeners(): bool
}Methods#
| Method | Description |
|---|---|
trigger | Calls the listeners with $args, then the once() listeners, which are forgotten after that. |
listen | Calls $listeners every time the event triggers. |
once | Calls $listeners the next time the event triggers, and not after. |
off | Removes $listeners, whether they were added with listen() or once(). |
hasListeners | Returns true if any listener is registered, with listen() or once(). |
Examples#
$onMessage = new phasync\Util\Event();
$onMessage->listen(function (string $data, bool $binary) {
echo "got $data\n";
});
$onMessage->once(fn () => print("first message only\n"));
$onMessage->trigger('hello', false); // got hello, then: first message only
$onMessage->trigger('again', false); // got againSee also#
Event::listenCalls$listenersevery time the event triggers.Event::triggerCalls the listeners with$args, then theonce()listeners, which are forgotten after that.