Skip to content

Instantly share code, notes, and snippets.

/emit_once.diff Secret

Created December 10, 2014 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2070c161523bd06812a1 to your computer and use it in GitHub Desktop.
Save anonymous/2070c161523bd06812a1 to your computer and use it in GitHub Desktop.
diff --git a/lib/Mojo/Content.pm b/lib/Mojo/Content.pm
index 50255e8..add63d1 100644
--- a/lib/Mojo/Content.pm
+++ b/lib/Mojo/Content.pm
@@ -295,7 +295,7 @@ sub _parse_until_body {
$self->{raw_size} += length($chunk //= '');
$self->{pre_buffer} .= $chunk;
$self->_parse_headers if ($self->{state} ||= 'headers') eq 'headers';
- $self->emit('body') if $self->{state} ne 'headers' && !$self->{body}++;
+ $self->emit_once('body') if $self->{state} ne 'headers';
}
1;
diff --git a/lib/Mojo/EventEmitter.pm b/lib/Mojo/EventEmitter.pm
index 794decf..09007cb 100644
--- a/lib/Mojo/EventEmitter.pm
+++ b/lib/Mojo/EventEmitter.pm
@@ -22,6 +22,8 @@ sub emit {
return $self;
}
+sub emit_once { $_[0]{once}{$_[1]}++ ? shift : shift->emit(@_) }
+
sub has_subscribers { !!@{shift->{events}{shift()} || []} }
sub on {
@@ -135,6 +137,13 @@ Subscribe to L</"error"> event.
Emit event.
+=head2 emit_once
+
+ $e = $e->emit_once('foo');
+ $e = $e->emit_once('foo', 123)
+
+Emit event only once.
+
=head2 has_subscribers
my $bool = $e->has_subscribers('foo');
diff --git a/lib/Mojo/Message.pm b/lib/Mojo/Message.pm
index 244aa7d..51b1ff0 100644
--- a/lib/Mojo/Message.pm
+++ b/lib/Mojo/Message.pm
@@ -89,7 +89,7 @@ sub extract_start_line {
sub finish {
my $self = shift;
$self->{state} = 'finished';
- return $self->{finished}++ ? $self : $self->emit('finish');
+ return $self->emit_once('finish');
}
sub fix_headers {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment