socketioMEANseed/www/bower_components/angular-socket-io/socket.js
www/bower_components/angular-socket-io/socket.jsRaw
1/*
2 * @license
3 * angular-socket-io v0.7.0
4 * (c) 2014 Brian Ford http://briantford.com
5 * License: MIT
6 */
7
8angular.module('btford.socket-io', []).
9 provider('socketFactory', function () {
10
11 'use strict';
12
13 // when forwarding events, prefix the event name
14 var defaultPrefix = 'socket:',
15 ioSocket;
16
17 // expose to provider
18 this.$get = ['$rootScope', '$timeout', function ($rootScope, $timeout) {
19
20 var asyncAngularify = function (socket, callback) {
21 return callback ? function () {
22 var args = arguments;
23 $timeout(function () {
24 callback.apply(socket, args);
25 }, 0);
26 } : angular.noop;
27 };
28
29 return function socketFactory (options) {
30 options = options || {};
31 var socket = options.ioSocket || io.connect();
32 var prefix = options.prefix === undefined ? defaultPrefix : options.prefix ;
33 var defaultScope = options.scope || $rootScope;
34
35 var addListener = function (eventName, callback) {
36 socket.on(eventName, callback.__ng = asyncAngularify(socket, callback));
37 };
38
39 var addOnceListener = function (eventName, callback) {
40 socket.once(eventName, callback.__ng = asyncAngularify(socket, callback));
41 };
42
43 var wrappedSocket = {
44 on: addListener,
45 addListener: addListener,
46 once: addOnceListener,
47
48 emit: function (eventName, data, callback) {
49 var lastIndex = arguments.length - 1;
50 var callback = arguments[lastIndex];
51 if(typeof callback == 'function') {
52 callback = asyncAngularify(socket, callback);
53 arguments[lastIndex] = callback;
54 }
55 return socket.emit.apply(socket, arguments);
56 },
57
58 removeListener: function (ev, fn) {
59 if (fn && fn.__ng) {
60 arguments[1] = fn.__ng;
61 }
62 return socket.removeListener.apply(socket, arguments);
63 },
64
65 removeAllListeners: function() {
66 return socket.removeAllListeners.apply(socket, arguments);
67 },
68
69 disconnect: function (close) {
70 return socket.disconnect(close);
71 },
72
73 connect: function() {
74 return socket.connect();
75 },
76
77 // when socket.on('someEvent', fn (data) { ... }),
78 // call scope.$broadcast('someEvent', data)
79 forward: function (events, scope) {
80 if (events instanceof Array === false) {
81 events = [events];
82 }
83 if (!scope) {
84 scope = defaultScope;
85 }
86 events.forEach(function (eventName) {
87 var prefixedEvent = prefix + eventName;
88 var forwardBroadcast = asyncAngularify(socket, function () {
89 Array.prototype.unshift.call(arguments, prefixedEvent);
90 scope.$broadcast.apply(scope, arguments);
91 });
92 scope.$on('$destroy', function () {
93 socket.removeListener(eventName, forwardBroadcast);
94 });
95 socket.on(eventName, forwardBroadcast);
96 });
97 }
98 };
99
100 return wrappedSocket;
101 };
102 }];
103 });