Created
July 17, 2012 17:19
-
-
Save lukegb/3130662 to your computer and use it in GitHub Desktop.
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
angular.module('mainApp', ['websocketBackend']).config(function($routeProvider) { | |
}); | |
function NowPlayingCtrl($scope, Socket) { | |
var that = this; | |
$scope.state = 'stop'; | |
Socket.on('playback_state_change', function(newState) { | |
$scope.state = newState; | |
}); | |
} |
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
var mB = angular.module('websocketBackend', []); | |
mB.factory('Socket', function($rootScope) { | |
var socket; | |
var boundMagic = {}; | |
var reconnectInterval = 0; | |
var hasOpened = false; | |
var rootScope = aRootScope; | |
function callListeners(eventName, data) { | |
console.log("DESPATCH", eventName, data, boundMagic); | |
if (boundMagic[eventName] === undefined) return; | |
rootScope.$apply(function() { | |
for (var i in boundMagic[eventName]) { | |
var thisFunc = boundMagic[eventName][i]; | |
thisFunc(data); | |
} | |
}); | |
rootScope.$digest(); | |
} | |
function reconnect() { | |
socket = new WebSocket("wss://websocket_test.local:4345/ws"); | |
socket.onopen = function() { | |
reconnectInterval = 100; | |
hasOpened = true; | |
}; | |
socket.onclose = function() { | |
if (hasOpened) | |
callListeners('close'); | |
hasOpened = false; | |
setInterval(reconnect, reconnectInterval); | |
}; | |
socket.onmessage = function(evt) { | |
console.log("WS:", evt.data); | |
var eventName = evt.data.substring(0, evt.data.indexOf(' ')).toLowerCase(); | |
var eventData = evt.data.substring(evt.data.indexOf(' ') + 1); | |
if (eventName == "playlist_add") { | |
// two split! | |
var playlistPosition = eventData.substring(0, eventData.indexOf(' ')); | |
var newSong = JSON.parse(eventData.substring(eventData.indexOf(' ') + 1)); | |
eventData = {position: playlistPosition, song: newSong}; | |
} else if (eventData[0] == '{') { // this is a cheaty hack. Ah well. | |
eventData = JSON.parse(eventData); | |
} | |
callListeners(eventName, eventData); | |
} | |
} | |
reconnect(); | |
var Socket = { | |
on: function(eventName, fn) { | |
if (boundMagic[eventName] === undefined) | |
boundMagic[eventName] = []; | |
boundMagic[eventName].push(fn); | |
} | |
}; | |
console.log(Socket); | |
return Socket; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment