Created
December 30, 2013 09:00
-
-
Save nl5887/8179591 to your computer and use it in GitHub Desktop.
AngularJS websocket factory
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.factory('socket', function ($rootScope) { | |
var socket = new WebSocket("ws://localhost:8000/data"); | |
return { | |
onopen: function (callback) { | |
socket.onopen = function () { | |
$rootScope.$apply(function () { | |
callback.apply(socket); | |
}); | |
}; | |
}, | |
onmessage: function (callback) { | |
socket.onmessage = function (e) { | |
var data = e.data; | |
$rootScope.$apply(function () { | |
if (callback) { | |
callback.apply(socket, [data]); | |
} | |
}); | |
} | |
}, | |
onerror: function (callback) { | |
socket.onerror = function (error) { | |
$rootScope.$apply(function () { | |
if (callback) { | |
callback.apply(socket, [error]); | |
} | |
}); | |
}; | |
}, | |
send: function (message) { | |
socket.send(message); | |
} | |
}; | |
}); | |
/* | |
Usage: | |
app.controller('AppController', ['$rootScope', '$scope', '$log', 'socket', function($rootScope, $scope, $location, $log, socket) { | |
socket.onopen(function () { | |
}); | |
socket.onerror(function (error) { | |
$log.error(error); | |
}); | |
socket.onmessage(function (message) { | |
$log.info(message); | |
}); | |
socket.send('message); | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment