Skip to content

Commit 0a9c339

Browse files
committed
breaking: fix transmits after reconnecting;
- requires the `new` syntax
1 parent 6d8095a commit 0a9c339

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/index.js

+18-9
Original file line numberDiff line numberDiff line change
@@ -3,40 +3,49 @@ function noop() {}
33
export default function (url, opts) {
44
opts = opts || {};
55

6-
let k, ws, num, $={};
6+
let k, ws, num, $={}, self=this;
77
let ms=opts.timeout || 1e3, max=opts.maxAttempts || Infinity;
88

99
$.onmessage = opts.onmessage || noop;
1010

1111
$.onclose = e => {
12-
(e.code !== 1e3 && e.code !== 1005) && $.reconnect(e);
12+
(e.code !== 1e3 && e.code !== 1005) && self.reconnect(e);
1313
(opts.onclose || noop)(e);
1414
};
1515

1616
$.onerror = e => {
17-
(e && e.code==='ECONNREFUSED') ? $.reconnect(e) : (opts.onerror || noop)(e);
17+
(e && e.code==='ECONNREFUSED') ? self.reconnect(e) : (opts.onerror || noop)(e);
1818
};
1919

2020
$.onopen = e => {
2121
num=0; (opts.onopen || noop)(e);
2222
};
2323

24-
$.open = () => {
24+
self.open = () => {
2525
ws = new WebSocket(url, opts.protocols);
2626
for (k in $) ws[k] = $[k];
27-
return ws;
2827
};
2928

30-
$.reconnect = e => {
29+
self.reconnect = e => {
3130
(++num < max) && setTimeout(_ => {
3231
(opts.onreconnect || noop)(e);
33-
$.open();
32+
self.open();
3433
}, ms);
3534
};
3635

37-
$.json = x => {
36+
self.json = x => {
3837
ws.send(JSON.stringify(x));
3938
};
4039

41-
return $.open();
40+
self.send = x => {
41+
ws.send(x);
42+
};
43+
44+
self.close = (x, y) => {
45+
ws.close(x, y);
46+
};
47+
48+
self.open(); // init
49+
50+
return self;
4251
}

0 commit comments

Comments
 (0)