Skip to content

Instantly share code, notes, and snippets.

@robertjd
Created June 22, 2012 17:23
Show Gist options
  • Save robertjd/2974075 to your computer and use it in GitHub Desktop.
Save robertjd/2974075 to your computer and use it in GitHub Desktop.
socket.io service as controller
;
(function(exports, undefined) {
angular.module('module.Socket', [], function($provide) {
$provide.factory('Socket', ['$rootScope', function socketController($rootScope) {
var scope = $rootScope.$new()
scope.socket = io.connect('/')
scope.send = function(message) {
try {
var m = JSON.stringify(message)
} catch (e) {
console.warn('Could not JSON.stringify message', message)
}
scope.socket.send(m)
}
scope.socket.on('message', messageHandler)
scope.socket.on('connect', connectHandler)
function connectHandler() {
scope.$emit('connect')
}
function messageHandler(message) {
if (typeof message === 'string') {
try {
var m = JSON.parse(message)
} catch (e) {
console.warn('Could not parse message as JSON', message)
return
}
if (typeof m.e === 'string') {
var d = typeof m.d === 'object' ? m.d : {}
if (typeof m.e === 'string') {
scope.$emit(m.e, m)
}
}
}
}
return scope
}])
}).run(['Socket', function(Socket) {}]);
})(window, undefined);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment