wiki:WhyPadreNeedsMoose

Version 6 (modified by azawawi, 3 years ago) (diff)

--

use v5.10;

package Padre::Document;
use Moose;
sub event_key_up { say "event_key_up fired"; }
no Moose;
1;

package NeedsKeyUpEvent;
use Moose::Role;
requires 'event_key_up';
before 'event_key_up' => sub { say q{before event_key_up}; };
after 'event_key_up'  => sub { say q{after event_key_up}; };
no Moose::Role;
1;

package main;
my $p = Padre::Document->new;
NeedsKeyUpEvent->meta->apply($p);
$p->event_key_up;
say "-----";
Padre::Document->new->event_key_up;

=>

before event_key_up
event_key_up fired
after event_key_up
-----
event_key_up fired

Using Moo will also do the trick:

use v5.10;

package Padre::Document;

sub new {
  my $class = shift;
  $class = ref $class if ref $class;
  my $self = bless {}, $class;
  $self;
}

1;

sub event_key_up { say "event_key_up fired"; }

1;

package NeedsKeyUpEvent;
use Role::Tiny;
requires 'event_key_up';
before 'event_key_up' => sub { say q{before event_key_up}; };
after 'event_key_up'  => sub { say q{after event_key_up}; };
1;

package main;
my $p = Padre::Document->new;
Role::Tiny->apply_roles_to_object($p, qw(NeedsKeyUpEvent));
$p->event_key_up;
say "-----";
Padre::Document->new->event_key_up;