Skip to content

Instantly share code, notes, and snippets.

@hussachai
Last active January 27, 2016 19:39
Show Gist options
  • Save hussachai/8a7cb2168b0c38f999c7 to your computer and use it in GitHub Desktop.
Save hussachai/8a7cb2168b0c38f999c7 to your computer and use it in GitHub Desktop.
var socket = null
function subscribe(channel) {
var subscribeUrl = jsRoutes.controllers.Application.subscribe().webSocketURL() + "?channel=" + channel
console.log("Subscribed to: " + subscribeUrl)
socket = new WebSocket(subscribeUrl)
socket.onmessage = function(event) {
$("#messages" ).prepend("<div>" + event.data + "</div>")
}
socket.onclose = function(event) {
console.log(event)
}
}
$(document).ready(function(){
subscribe($("#channel" ).val())
$("#channel" ).change(function(){
if(socket) socket.close()
subscribe($(this ).val())
})
$("#submit" ).click(function(){
var publishUrl = jsRoutes.controllers.Application.publish($("#channel" ).val() ).url
jQuery.post(publishUrl, "message="+$("#message" ).val() ).success(function(){
$("#message" ).val("")
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment