NAME
MooX::EventHandler - Use Moo modules with event handlers.
SYNOPSIS
package Daisy;
use Moo;
use MooX::EventHandler;
has_event 'on_abattoir';
sub on_abattoir { die } # Cannot be replaced by users
has_event 'on_new_grass' => builder => sub { sub { # Yes, two
my $self = shift;
$self->eat();
}};
has_event 'on_bull' => builder => 'make_calf';
sub make_calf { sub { # Two again
Daisy->new();
}}
DESCRIPTION
Exports a function has_event
which creates an attribute with settings useful for writing event-driven code.
Specifically:
Event attributes are lazy by default.
The attribute is named
_${event}_event
so that$event()
calls the event handler rather than returning the coderef which implements it. Theinit_arg
remains$event
and the default builder_build_$event
.required
now means that the default event handler will die, not that a handler must be passed to the constructor.(Optionally) Another attribute is added to the class which returns a listref of this object's event.
BUGS
- Tracked events do not work correctly with inheritence or roles.
- Double-layered subs are ugly.
- This was written primarily for use with IO::Async and has not been tested with other event libraries.
- Overriding/updating attribute options in subclasses has no explicit support and probably doesn't work.
- There are no tests.
EVENT ATTRIBUTES
Event attributes are simply regular Moo attributes with defaults useful for writing event-driven code and as such can be treated like any other attribute, but see "BUGS".
There are 3 different ways to assign handlers to an event.
- A lazy builder.
-
A coderef can be returned from an event attribute's
builder
ordefault
in the usual way. - Passed to the constructor.
-
Coderefs can be passed to the constructor with the name of the event just like any other attribute.
- Directly in the object.
-
The event handler can be installed as a regular method in the class. This overrides the ability to pass event handlers to the constructor.
EVENT TRACKING
If MooX::EventHandler is imported with the -tracked
option and the name of an attribute, that attribute is created and set up to return a list of all of the object's events. This feature is buggy and does not work properly with inheritence.
package Foo;
use Moo;
use MooX::EventHandler -tracked => 'all_events';
has_event 'on_foo';
has_event 'on_bar';
# Foo->new->all_events will now return ['on_foo', 'on_bar'];
SEE ALSO
AUTHOR
Matthew King <chohag@jtan.com>