Last active
May 13, 2016 00:32
-
-
Save jberger/c4515eb8399f356736528dbc5af115f2 to your computer and use it in GitHub Desktop.
Port of the Mojo::Pg chat example to Vue.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For comparison: https://github.com/kraih/mojo-pg/blob/master/examples/chat.pl