The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

MooseX::Role::Listenable - A parameterized role for observable objects

SYNOPSIS

# a class with an observable feature- notifies observers
# when door opened
package Car;
use Moose;
with 'MooseX::Role::Listenable' => {event => 'door_opened'};
sub open_door {
    ... # actually open the door
    $self->door_opened; # notify observers
}

# an observer class that can listen to door_opened events
package Dashboard;
use Moose;
sub door_opened { print "Got door_opened event!\n" }

# attach observer to observable
$car->add_door_opened_listener($dashboard);

# detach
$car->remove_door_opened_listener($dashboard);

DESCRIPTION

A simple implemenation of the observable pattern. By adding this to a class:

with 'MooseX::Role::Listenable' => {event => 'some_event_name'};

You are making the class observable for the event 'some_event_name'. You can call the method some_event_name() on the object, and all listeners added with add_some_event_name_listener() will be notified. Listeners will be notified by calling their method some_event_name().

Note the list of listeners is a Set::Object::Weak, so be sure to keep a reference to them somewhere else.

SEE ALSO

Class::Listener, Class::Observable, and Aspect::Library::Listenable.

AUTHOR

Ran Eilam <eilara@cpan.org>

COPYRIGHT

Ran Eilam <eilara@cpan.org>

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.