DOKK / manpages / debian 12 / libmojolicious-perl / Mojo::EventEmitter.3pm.en
Mojo::EventEmitter(3pm) User Contributed Perl Documentation Mojo::EventEmitter(3pm)

Mojo::EventEmitter - Event emitter base class

  package Cat;
  use Mojo::Base 'Mojo::EventEmitter', -signatures;
  # Emit events
  sub poke ($self) { $self->emit(roar => 3) }
  package main;
  # Subscribe to events
  my $tiger = Cat->new;
  $tiger->on(roar => sub ($tiger, $times) { say 'RAWR!' for 1 .. $times });
  $tiger->poke;

Mojo::EventEmitter is a simple base class for event emitting objects.

Mojo::EventEmitter can emit the following events.

  $e->on(error => sub ($e, $err) {...});

This is a special event for errors, it will not be emitted directly by this class, but is fatal if unhandled. Subclasses may choose to emit it, but are not required to do so.

  $e->on(error => sub ($e, $err) { say "This looks bad: $err" });

Mojo::EventEmitter inherits all methods from Mojo::Base and implements the following new ones.

  $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 ($e, @args) {...});

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

Subscribe to event and unsubscribe again after it has been emitted once.

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

  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.

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

  MOJO_EVENTEMITTER_DEBUG=1

Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.

2022-12-22 perl v5.36.0