package f00li5h::Events; use Class::Std; { use strict; my %callbacks :ATTR(); =head1 register_callback $object->register_callback( event_name => $subref ); the subref will be passed a list of args provided when the event is triggered, and will be protected in an eval block. =cut sub register_callback { my($self, $name, $subref) = @_; unless ( ref $subref eq 'CODE' ) { use Data::Dumper; warn "You call that a callback? it's not a real coderef, so i'm going to ignore it! :" . Dumper( $subref ); return; } $callbacks{ ident $self }->{ $name } = $subref; } =head1 trigger_event trigger an event, will return the exception or the result of the sub $object->trigger_event( event_name => $argref); $object->trigger_event( event_name => [ $user, $data, $foos ...] ); =cut sub trigger_event { my($self, $name, @data) = @_; warn "Callback '$name' not registered" if not defined $callbacks{ ident $self }-> { $name }; my $result; eval { $result = $callbacks{ ident $self }->{ $name }->( @data ); }; return $@ if $@; # if calling the handler fails, return the exception return $result; # toherwise return what the sub returned } }