-
Notifications
You must be signed in to change notification settings - Fork 53
/
index.js
87 lines (68 loc) · 1.76 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict';
import { DeviceEventEmitter, NativeModules, Platform } from 'react-native';
let SocketIO = NativeModules.SocketIO;
class Socket {
constructor (host, config) {
if (typeof host === 'undefined')
throw 'Hello there! Could you please give socket a host, please.';
if (typeof config === 'undefined')
config = {};
this.sockets = SocketIO;
this.isConnected = false;
this.handlers = {};
this.onAnyHandler = null;
this.deviceEventSubscription = DeviceEventEmitter.addListener(
'socketEvent', this._handleEvent.bind(this)
);
// Set default handlers
this.defaultHandlers = {
connect: () => {
this.isConnected = true;
},
disconnect: () => {
this.isConnected = false;
}
};
// Set initial configuration
this.sockets.initialize(host, config);
}
_handleEvent (event) {
if (this.handlers.hasOwnProperty(event.name)) {
this.handlers[event.name](
(event.hasOwnProperty('items')) ? event.items : null
);
}
if (this.defaultHandlers.hasOwnProperty(event.name)) {
this.defaultHandlers[event.name]();
}
if (this.onAnyHandler) this.onAnyHandler(event);
}
connect () {
this.sockets.connect();
}
on (event, handler) {
this.handlers[event] = handler;
if (Platform.OS === 'android') {
this.sockets.on(event);
}
}
onAny (handler) {
this.onAnyHandler = handler;
}
emit (event, data) {
this.sockets.emit(event, data);
}
joinNamespace (namespace) {
this.sockets.joinNamespace(namespace);
}
leaveNamespace () {
this.sockets.leaveNamespace();
}
disconnect () {
this.sockets.disconnect();
}
reconnect () {
this.sockets.reconnect();
}
}
module.exports = Socket;