-
-
Save nodokodo/3937508 to your computer and use it in GitHub Desktop.
socket.io service as controller
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
; | |
(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