Skip to content

Instantly share code, notes, and snippets.

Created April 18, 2013 00:33
Show Gist options
  • Save anonymous/5408921 to your computer and use it in GitHub Desktop.
Save anonymous/5408921 to your computer and use it in GitHub Desktop.
(function (window, app, undefined) {
'use strict';
app.factory('socket', ['$rootScope', function ($rootScope) {
var socket = $rootScope.socket;
var onCallback = function (callback, args) {
$rootScope.$apply(function () {
callback.apply(socket, args);
});
};
var emitCallback = function (callback, args) {
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
};
return {
on: function (channel, callback) {
socket.on(channel, function () {
onCallback(callback, arguments)
});
},
emit: function (channel, data, callback) {
// in some instances angular leaves .$$hashKey, etc. on the model, etc. fromJson(toJson( strips the proprietary tags
// & socket.io can then do it's stringify magic
socket.emit(channel, angular.fromJson(angular.toJson(data)), function () {
emitCallback(callback, arguments);
});
},
of: function (name) {
return {
on: function (channel, callback) {
socket.of(name).on(channel, function () {
onCallback(callback, arguments)
});
},
emit: function (channel, data, callback) {
socket.of(name).emit(channel, angular.fromJson(angular.toJson(data)), function () {
emitCallback(callback, arguments);
});
}
}
}
};
}]);
})(window, window.app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment