Skip to content

Instantly share code, notes, and snippets.

@lrvick
Last active December 14, 2015 19:09
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lrvick/5134870 to your computer and use it in GitHub Desktop.
Save lrvick/5134870 to your computer and use it in GitHub Desktop.
Websocket AngularJS controller/services pattern
app.controller( 'AppCtrl', function ($scope, socket) {
socket.onopen(
function(){
console.log('Socket is connected :D')
}
)
socket.onclose(
function(){
console.log('Socket is disconnected :(')
}
)
})
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
})
})
@adilwali
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment