-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
69 lines (58 loc) · 1.35 KB
/
index.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
var Emitter = require('component-emitter')
module.exports = function wsEvents (sock) {
var listeners = new Emitter()
var onopenHandlers = []
function onmessage (event) {
var json, args
try {
json = JSON.parse(event.data)
args = [json.t].concat(json.a)
} catch (e) {
onerror(e)
return
}
listeners.emit.apply(listeners, args)
}
function onerror (err) {
listeners.emit('error')
}
function onopen () {
onopenHandlers.forEach(function (fn) {
fn()
})
onopenHandlers = []
}
function whenOpen (fn) {
if (sock.readyState === sock.constructor.OPEN) {
fn()
} else {
onopenHandlers.push(fn)
}
}
sock.onmessage = onmessage
sock.onerror = onerror
sock.onopen = onopen
function emit (type) {
var args = Array.prototype.slice.call(arguments, 1)
whenOpen(function () {
sock.send(JSON.stringify({ t: type, a: args }))
})
return events
}
function on (type, cb) {
listeners.on(type, cb)
return events
}
function off (type, cb) {
listeners.off(type, cb)
return events
}
var events = Object.create(sock)
events.socket = sock
events.emit = emit
events.on = on
events.off = off
events.listeners = listeners.listeners.bind(listeners)
events.hasListeners = listeners.hasListeners.bind(listeners)
return events
}