Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

adilwali commented Mar 11, 2013

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
You can’t perform that action at this time.