Created
April 12, 2014 11:25
-
-
Save witoldsz/10531004 to your computer and use it in GitHub Desktop.
Prototype of AngularJS service for socket.io v.0.9.x
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
(function(module) { | |
"use strict"; | |
// THIS IS ALPHA VERSION, JUST A SNIPPET OF A PROTOTYPE | |
module.factory('socket', function($rootScope, $q, $browser) { | |
var self = { | |
_iosocket: io.connect(), | |
_parse: function(data) { | |
return angular.isString(data) && /\{.*\}|\[.*\]/.test(data) | |
? JSON.parse(data) | |
: data; | |
}, | |
/** | |
* Registers a callback fired each time server emits an event. | |
* @param {String} name of event | |
* @param {function} callback | |
*/ | |
on: function(name, callback) { | |
this._iosocket.on(name, function(data) { | |
$rootScope.$apply(function() { | |
callback(self._parse(data)); | |
}); | |
}); | |
}, | |
/** | |
* Emits an event to server. | |
* @param {String} name of event | |
* @param {...*} [eventargs] optional arguments | |
* @returns {promise} which resolves with a: | |
* - JSON parsed response when response is a string like {...} or [...], or | |
* - response as-is otherwise | |
*/ | |
emit: function(name) { | |
var defer = $q.defer(); | |
$browser.$$incOutstandingRequestCount(); | |
var args = Array.prototype.slice.call(arguments); | |
//last argument is a server confirmation callback | |
this._iosocket.emit.apply(this._iosocket, args.concat(function(response) { | |
$browser.$$completeOutstandingRequest(function() { | |
defer.resolve(self._parse(response)); | |
}); | |
})); | |
return defer.promise; | |
}, | |
/** | |
* Emits an event asking for joining the room and registers a callback fired on each event with the same name. | |
* @param {String} name of room and event | |
* @param {function} callback | |
* @see {@link on} | |
*/ | |
joinRoom: function(name, callback) { | |
this.on(name, callback); | |
join(); | |
this._iosocket.on('reconnect', join); | |
function join() { | |
self._iosocket.emit('enter room: ' + name); | |
} | |
} | |
}; | |
return self; | |
}); | |
})(angular.module('socket', [])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment