Last active
December 14, 2015 19:09
-
-
Save lrvick/5134870 to your computer and use it in GitHub Desktop.
Websocket AngularJS controller/services pattern
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
app.controller( 'AppCtrl', function ($scope, socket) { | |
socket.onopen( | |
function(){ | |
console.log('Socket is connected :D') | |
} | |
) | |
socket.onclose( | |
function(){ | |
console.log('Socket is disconnected :(') | |
} | |
) | |
}) |
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
efine(['app', 'sockjs'], function (app, SockJS) { | |
return app.value('version', '0.1').factory('socket', function ($rootScope) { | |
var createSocket = function () { | |
var port = (location.port != 80) ? ':'+location.port : '' | |
var socket = new SockJS('http://' + document.domain + '' + port + '/sockjs', '', { | |
'debug': true | |
}) | |
socket.onopen = function () { | |
var args = arguments; | |
$rootScope.$apply(function () { | |
self.socket_handlers.onopen.apply(socket, args) | |
}) | |
} | |
socket.onmessage = function (data) { | |
var args = arguments; | |
$rootScope.$apply(function () { | |
self.socket_handlers.onmessage.apply(socket, args) | |
}) | |
} | |
socket.onclose = function () { | |
setTimeout(function () { | |
createSocket(); | |
}, 1000); | |
var args = arguments; | |
$rootScope.$apply(function () { | |
self.socket_handlers.onclose.apply(socket, args) | |
}) | |
} | |
return socket | |
} | |
self.socket_handlers = {} | |
var methods = | |
{ onopen: function (callback) { | |
self.socket_handlers.onopen = callback | |
} | |
, onmessage: function (callback) { | |
self.socket_handlers.onmessage = callback | |
} | |
, onclose: function (callback) { | |
self.socket_handlers.onclose = callback | |
} | |
} | |
var socket = createSocket() | |
return methods | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'd consider creating a master sockjs object here. Then you can nest objects like 'socket_handlers' and 'methods' underneath that. And you can return the whole object as part of the service.