Skip to content

Instantly share code, notes, and snippets.

@jberger
Last active May 13, 2016 00:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/c4515eb8399f356736528dbc5af115f2 to your computer and use it in GitHub Desktop.
Save jberger/c4515eb8399f356736528dbc5af115f2 to your computer and use it in GitHub Desktop.
Port of the Mojo::Pg chat example to Vue.js
use Mojolicious::Lite;
use Mojo::Pg;
helper pg => sub { state $pg = Mojo::Pg->new('postgresql://postgres@/test') };
get '/' => 'chat';
websocket '/channel' => sub {
my $c = shift;
$c->inactivity_timeout(3600);
# Forward messages from the browser to PostgreSQL
$c->on(message => sub { shift->pg->pubsub->notify(mojochat => shift) });
# Forward messages from PostgreSQL to the browser
my $cb = $c->pg->pubsub->listen(mojochat => sub { $c->send(pop) });
$c->on(finish => sub { shift->pg->pubsub->unlisten(mojochat => $cb) });
};
app->start;
__DATA__
@@ chat.html.ep
%= javascript 'https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.20/vue.js'
<div id="chat">
<form @submit.prevent="send"><input v-model="current"></form>
<div id="log"><p v-for="m in messages">{{m}}</p></div>
</div>
<script>
var ws = new WebSocket('<%= url_for('channel')->to_abs %>');
var vm = new Vue({
el: '#chat',
data: {
current: '',
messages: [],
},
methods: {
send: function() {
ws.send(this.current);
this.current = '';
},
},
});
ws.onmessage = function (e) { vm.messages.push(e.data) };
</script>
@jberger
Copy link
Author

jberger commented Apr 7, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment