Beam-Emitter

 view release on metacpan or  search on metacpan

README  view on Meta::CPAN

Beam::Emitter

This role is used by classes that want to add callback hooks to allow
users to add new behaviors to their objects. These hooks are called
"events". A subscriber registers a callback for an event using the
"subscribe" or "on" methods. Then, the class can call those callbacks by
emitting an event with the emit() method.

Using the Beam::Event class, subscribers can stop an event from being
processed, or prevent the default action from happening.

  Using Beam::Event

Beam::Event is an event object with some simple methods to allow
subscribers to influence the handling of the event. By calling the stop
method, subscribers can stop all futher handling of the event. By
calling the the stop_default method, subscribers can allow other
subscribers to be notified about the event, but let the emitter know
that it shouldn't continue with what it was going to do.

For example, let's build a door that notifies when someone tries to open
it. Different instances of a door should allow different checks before
the door opens, so we'll emit an event before we decide to open.

    package Door;
    use Moo;
    with 'Beam::Emitter';

    sub open {
        my ( $self, $who ) = @_;
        my $event = $self->emit( 'before_open' );
        return if $event->is_default_stopped;
        $self->open_the_door;
    }

    package main;
    my $door = Door->new;
    $door->open;

Currently, our door will open for anybody. But let's build a door that
only open opens after noon (to keep us from having to wake up in the
morning).

    use Time::Piece;
    my $restful_door = Door->new;

    $restful_door->on( before_open => sub {
        my ( $event ) = @_;

        my $time = Time::Piece->now;
        if ( $time->hour < 12 ) {
            $event->stop_default;
        }

    } );

    $restful_door->open;

By calling stop_default, we set the is_default_stopped flag, which the
door sees and decides not to open.

  Using Custom Events

The default "Beam::Event" is really only useful for notifications. If
you want to give your subscribers some data, you need to create a custom
event class. This allows you to add attributes and methods to your



( run in 1.067 second using v1.01-cache-2.11-cpan-d8267643d1d )