mirror of
https://github.com/taobataoma/meanTorrent.git
synced 2026-01-15 03:42:23 +01:00
67 lines
1.4 KiB
JavaScript
67 lines
1.4 KiB
JavaScript
(function () {
|
|
'use strict';
|
|
|
|
// Create the Socket.io wrapper service
|
|
angular
|
|
.module('core')
|
|
.factory('Socket', Socket);
|
|
|
|
Socket.$inject = ['Authentication', '$state', '$timeout'];
|
|
|
|
function Socket(Authentication, $state, $timeout) {
|
|
var service = {
|
|
connect: connect,
|
|
disconnect: disconnect,
|
|
emit: emit,
|
|
on: on,
|
|
removeListener: removeListener,
|
|
socket: null
|
|
};
|
|
|
|
connect();
|
|
|
|
return service;
|
|
|
|
// Connect to Socket.io server
|
|
function connect() {
|
|
// Connect only when authenticated
|
|
if (Authentication.user) {
|
|
service.socket = io();
|
|
}
|
|
}
|
|
|
|
// disconnect to Socket.io server
|
|
function disconnect() {
|
|
if (service.socket) {
|
|
service.socket.disconnect();
|
|
service.socket = null;
|
|
}
|
|
}
|
|
|
|
// Wrap the Socket.io 'emit' method
|
|
function emit(eventName, data) {
|
|
if (service.socket) {
|
|
service.socket.emit(eventName, data);
|
|
}
|
|
}
|
|
|
|
// Wrap the Socket.io 'on' method
|
|
function on(eventName, callback) {
|
|
if (service.socket) {
|
|
service.socket.on(eventName, function (data) {
|
|
$timeout(function () {
|
|
callback(data);
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
// Wrap the Socket.io 'removeListener' method
|
|
function removeListener(eventName) {
|
|
if (service.socket) {
|
|
service.socket.removeListener(eventName);
|
|
}
|
|
}
|
|
}
|
|
}());
|