Role::EventEmitter(3pm) | User Contributed Perl Documentation | Role::EventEmitter(3pm) |
Role::EventEmitter - Event emitter role
package Channel; use Moo; with 'Role::EventEmitter'; # Emit events sub send_message { my $self = shift; $self->emit(message => @_); } package main; # Subscribe to events my $channel_a = Channel->new; $channel_a->on(message => sub { my ($channel, $text) = @_; say "Received message: $text"; }); $channel_a->send_message('All is well');
Role::EventEmitter is a simple Role::Tiny role for event emitting objects based on Mojo::EventEmitter. This role can be applied to any hash-based object class such as those created with Class::Tiny, Moo, or Moose.
Role::EventEmitter can emit the following events.
$e->on(error => sub { my ($e, $err) = @_; ... });
This is a special event for errors, it will not be emitted directly by this role but is fatal if unhandled.
$e->on(error => sub { my ($e, $err) = @_; say "This looks bad: $err"; });
Role::EventEmitter composes the following methods.
$e = $e->catch(sub {...});
Subscribe to "error" event.
# Longer version $e->on(error => sub {...});
$e = $e->emit('foo'); $e = $e->emit('foo', 123);
Emit event.
my $bool = $e->has_subscribers('foo');
Check if event has subscribers.
my $cb = $e->on(foo => sub {...});
Subscribe to event.
$e->on(foo => sub { my ($e, @args) = @_; ... });
my $cb = $e->once(foo => sub {...});
Subscribe to event and unsubscribe again after it has been emitted once.
$e->once(foo => sub { my ($e, @args) = @_; ... });
my $f = $e->once_f('foo');
Subscribe to event as in "once", returning a Future that will be marked complete after it has been emitted once. Requires Future to be installed.
my $f = $e->once_f('foo')->on_done(sub { my ($e, @args) = @_; ... });
To unsubscribe the returned Future early, cancel it.
$f->cancel;
my $subscribers = $e->subscribers('foo');
All subscribers for event.
# Unsubscribe last subscriber $e->unsubscribe(foo => $e->subscribers('foo')->[-1]); # Change order of subscribers @{$e->subscribers('foo')} = reverse @{$e->subscribers('foo')};
$e = $e->unsubscribe('foo'); $e = $e->unsubscribe(foo => $cb);
Unsubscribe from event. Related Futures will also be cancelled.
You can set the "ROLE_EVENTEMITTER_DEBUG" environment variable to get some advanced diagnostics information printed to "STDERR".
ROLE_EVENTEMITTER_DEBUG=1
Report any issues on the public bugtracker.
Dan Book <dbook@cpan.org>
Code and tests adapted from Mojo::EventEmitter, an event emitter base class by the Mojolicious team.
Copyright (c) 2008-2015 Sebastian Riedel.
Copyright (c) 2015 Dan Book for adaptation to a role and further changes.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
Mojo::EventEmitter, Mixin::Event::Dispatch, Beam::Emitter, Event::Distributor
2021-12-10 | perl v5.32.1 |