-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient.js
More file actions
97 lines (97 loc) · 2.39 KB
/
client.js
File metadata and controls
97 lines (97 loc) · 2.39 KB
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
function io(url, options) {"use strict";
/*! (c) Andrea Giammarchi (ISC) */
if (typeof url === 'object') {
options = url || options;
url = options.url;
}
var SR = (options || {}).JSON || JSON;
var connected = false;
var queue = [];
var listeners = {};
var parts = new URL(url || location.href);
var socket = new WebSocket([
parts.protocol.replace('http', 'ws'),
'//',
parts.host,
'/pocket.io/'
].join(''));
socket.onopen = function (event) {
pocket.emit('connect');
connected = true;
while (queue.length)
socket.send(queue.shift());
};
socket.onmessage = function (event) {
var info = SR.parse(event.data);
var cbs = listeners[info.type];
if (info.type === 'connect') {
pocket.id = info.data;
emit(cbs);
}
else if (info.data)
emit(cbs, info.data);
else
emit(cbs);
};
socket.onerror = function (error) {
emit(listeners.error, error);
};
socket.onclose = function (event) {
socket = null;
emit(listeners.close);
};
var pocket = {
close: function () {
if (socket) socket.close();
return pocket;
},
emit: function (type, data) {
var json = SR.stringify({
type: type,
data: data
});
if (connected)
socket.send(json);
else
queue.push(json);
return pocket;
},
listeners: function (type) {
return listeners[type] || [];
},
hasListeners: function (type) {
return 0 < pocket.listeners(type).length;
},
on: function (type, callback) {
(listeners[type] || (listeners[type] = [])).push(callback);
return pocket;
},
once: function (type, callback) {
var current = listeners[type] || (listeners[type] = []);
current.push(
function once() {
current.splice(current.indexOf(once), 1);
callback.apply(this, arguments);
}
);
return pocket;
},
off: function (type, callback) {
var current = listeners[type] || [];
var i = current.indexOf(callback);
if (-1 < i) current.splice(i, 1);
return pocket;
},
send: function (data) {
return pocket.emit('message', data);
}
};
pocket.disconnect = pocket.close;
return pocket;
function emit(listeners) {
(listeners || []).forEach(
function (fn) { fn.apply(pocket, this); },
[].slice.call(arguments, 1)
);
}
}