NAME

Role::EventEmitter - Event emitter role

SYNOPSIS

package Cat;
use Moo;
with 'Role::EventEmitter';

# Emit events
sub poke {
  my $self = shift;
  $self->emit(roar => 3);
}

package main;

# Subscribe to events
my $tiger = Cat->new;
$tiger->on(roar => sub {
  my ($tiger, $times) = @_;
  say 'RAWR!' for 1 .. $times;
});
$tiger->poke;

DESCRIPTION

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.

EVENTS

Role::EventEmitter can emit the following events.

error

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

METHODS

Role::EventEmitter composes the following methods.

catch

$e = $e->catch(sub {...});

Subscribe to "error" event.

# Longer version
$e->on(error => sub {...});

emit

$e = $e->emit('foo');
$e = $e->emit('foo', 123);

Emit event.

has_subscribers

my $bool = $e->has_subscribers('foo');

Check if event has subscribers.

on

my $cb = $e->on(foo => sub {...});

Subscribe to event.

$e->on(foo => sub {
  my ($e, @args) = @_;
  ...
});

once

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) = @_;
  ...
});

subscribers

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

unsubscribe

$e = $e->unsubscribe('foo');
$e = $e->unsubscribe(foo => $cb);

Unsubscribe from event.

DEBUGGING

You can set the ROLE_EVENTEMITTER_DEBUG environment variable to get some advanced diagnostics information printed to STDERR.

ROLE_EVENTEMITTER_DEBUG=1

BUGS

Report any issues on the public bugtracker.

AUTHOR

Dan Book <dbook@cpan.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2015 by Dan Book.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)

SEE ALSO

Mojo::EventEmitter, Mixin::Event::Dispatch, Beam::Emitter