-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-socket-wrapper.js
100 lines (72 loc) · 2.84 KB
/
angular-socket-wrapper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
(function(window, angular, io, undefined) {'use strict';
angular.module('SocketWrapper', [])
.provider('$socket', function $socketProvider() {
var options = {
'force new connection': true,
port: 8010
},
host;
this._io = function(_io){
io = _io;
}
this.options = function(_options){
angular.extend(options, _options);
};
this.host = function(_host){
host = _host;
};
this.$get = ['$location', function($location){
host = host || ($location.protocol() + '://' + $location.host());
return new SocketWrapper(options);
}];
function SocketWrapper(options){
if (!io) return console.error('Socket.io is not found. Did you include script? It should be included before this script.')
this.socket = io.connect(host, options);
}
SocketWrapper.prototype = {
bind: function (scope){
var wrapper = this,
socket = wrapper.socket,
socketListeners = [];
// add listeners for already attached events on scope
angular.forEach(scope.$$listeners, function(listeners, name){
angular.forEach(listeners, function(listener){
socketListeners.push({
name: name,
fn: listener
});
socket.on(name, listener);
});
});
scope.$on('$destroy', removeListeners);
// override scope methods to catch binidngs
angular.forEach(['$on', '$emit'], function(method){
var fn = angular.bind(scope, scope[method]);
// scope.$on('$destroy')
scope[method] = function(name, listener){
socketListeners.push({
name: name,
fn: listener
});
wrapper[method].call(wrapper, name, listener);
fn.apply(scope, arguments);
}
});
function removeListeners(){
angular.forEach(socketListeners, function(val){
wrapper.$off(val.name, val.fn);
});
}
},
$off: function(name, listener){
this.socket.removeListener(name, listener);
},
$on: function(name, listener){
this.socket.on(name, listener);
},
$emit: function(name, args){
this.socket.emit(name, args);
}
};
});
})(window, window.angular, window.io);