Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Mojolicious::Plugin::EventSource;
- use Mojo::Base 'Mojolicious::Plugin';
- sub register {
- my $self = shift;
- my $app = shift;
- my $conf = shift;
- $conf->{ timeout } ||= 300;
- $app->routes->add_shortcut('event_source' => sub {
- my $self = shift;
- my @pars = map {
- if(ref $_ eq "CODE") {
- my $copy = $_;
- $_ = sub {
- my $self = shift;
- Mojo::IOLoop->stream($self->tx->connection)->timeout($conf->{ timeout });
- $self->res->headers->content_type('text/event-stream');
- $self->$copy(@_);
- };
- }
- $_;
- } @_;
- $app->routes->get( @_, "" );
- });
- $app->helper( 'event_source' => sub { $app->routes->event_source( @_ ) } );
- $app->helper( 'emit' => sub {
- my $self = shift;
- my $event = shift;
- my $data = shift;
- $self->write("event:$event\ndata: $data\n\n");
- });
- }
- 42;
- #### app.pl
- #!/usr/bin/env perl
- use Mojolicious::Lite;
- plugin 'Mojolicious::Plugin::EventSource';
- get '/' => 'index';
- event_source('/events' => sub {
- my $self = shift;
- print $self->tx, $/;
- my $id = Mojo::IOLoop->recurring(1 => sub {
- my $pips = int(rand 6) + 1;
- $self->emit("dice", $pips);
- });
- $self->on(finish => sub { print $/ x 3, "finish!!!", $/ x 3, Mojo::IOLoop->drop($id) });
- });
- app->start;
- __DATA__
- @@ index.html.ep
- <!doctype html><html>
- <head><title>Roll The Dice</title></head>
- <body>
- <script>
- var events = new EventSource('<%= url_for 'events' %>');
- // Subscribe to "dice" event
- events.addEventListener('dice', function(event) {
- document.body.innerHTML += event.data + '<br/>';
- }, false);
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement