-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.js
40 lines (40 loc) · 1.57 KB
/
io.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
module.exports = {
socketLog: {},
internals: [],
initialize(io) {
this.io = io;
io.on('connect', (socket) => {
socket.on('bind', (path) => {
const space = path === '' ? '0' : `0.${path}`;
console.log(`socket bond: ${space}`); // eslint-disable-line no-console
if (!this.socketLog[space]) this.socketLog[space] = [];
if (this.socketLog[space].indexOf(socket) < 0) {
this.socketLog[space].push(socket);
socket.on('disconnect', () => {
console.log(`socket disconnected: ${space}`); // eslint-disable-line no-console
this.socketLog[space].slice(this.socketLog[space].indexOf(socket), 1);
});
} else socket.count = (socket.count || 1) + 1;
});
socket.on('unbind', (path) => {
const space = path === '' ? '0' : `0.${path}`;
console.log(`socket disbound: ${space}`); // eslint-disable-line no-console
if (socket.count && socket.count > 1) {
socket.count -= 1;
} else this.socketLog[space].slice(this.socketLog[space].indexOf(socket), 1);
});
});
},
reportChanges(changes) {
Object.keys(changes).forEach((space) => {
const path = space === '0' ? '' : space.replace(/^0\./, '');
(this.socketLog[space] || []).forEach(socket => socket.emit('update', path, changes[space]));
this.internals.forEach((internal) => {
if (internal.pattern.test(path)) internal.callback(path, changes[space]);
});
});
},
pushInternal(pattern, callback) {
this.internals.push({ pattern, callback });
},
};