Skip to content

Commit

Permalink
improve subscribers method in Mojo::EventEmitter to allow subscribers…
Browse files Browse the repository at this point in the history
… to be modified more easily
  • Loading branch information
kraih committed Jun 26, 2015
1 parent 260db33 commit 235e802
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
2 changes: 2 additions & 0 deletions Changes
@@ -1,5 +1,7 @@

6.13 2015-06-26
- Improved subscribers method in Mojo::EventEmitter to allow subscribers to be
modified more easily.

6.12 2015-06-18
- Welcome to the Mojolicious core team Dan Book.
Expand Down
5 changes: 4 additions & 1 deletion lib/Mojo/EventEmitter.pm
Expand Up @@ -41,7 +41,7 @@ sub once {
return $wrapper;
}

sub subscribers { shift->{events}{shift()} || [] }
sub subscribers { shift->{events}{shift()} ||= [] }

sub unsubscribe {
my ($self, $name, $cb) = @_;
Expand Down Expand Up @@ -168,6 +168,9 @@ All subscribers for event.
# Unsubscribe last subscriber
$e->unsubscribe(foo => $e->subscribers('foo')->[-1]);
# Change order of subscribers
@{$e->subscribers('foo')} = reverse @{$e->subscribers('foo')};
=head2 unsubscribe
$e = $e->unsubscribe('foo');
Expand Down
14 changes: 13 additions & 1 deletion t/mojo/eventemitter.t
Expand Up @@ -132,9 +132,21 @@ is scalar @{$e->subscribers('foo')}, 0, 'no subscribers';
$e->emit('foo');
is $counter, 5, 'event was not emitted again';

# Pass by reference and assignment to $_
# Manipulate events
$e = Mojo::EventEmitter->new;
my $buffer = '';
push @{$e->subscribers('foo')}, sub { $buffer .= 'one' };
push @{$e->subscribers('foo')}, sub { $buffer .= 'two' };
push @{$e->subscribers('foo')}, sub { $buffer .= 'three' };
$e->emit('foo');
is $buffer, 'onetwothree', 'right result';
@{$e->subscribers('foo')} = reverse @{$e->subscribers('foo')};
$e->emit('foo');
is $buffer, 'onetwothreethreetwoone', 'right result';

# Pass by reference and assignment to $_
$e = Mojo::EventEmitter->new;
$buffer = '';
$e->on(one => sub { $_ = $_[1] .= 'abc' . $_[2] });
$e->on(one => sub { $_[1] .= '123' . pop });
is $buffer, '', 'no result';
Expand Down

0 comments on commit 235e802

Please sign in to comment.