forked from gcrabtree/react-native-socketio
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
105 lines (83 loc) · 2.28 KB
/
index.js
File metadata and controls
105 lines (83 loc) · 2.28 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
98
99
100
101
102
103
104
105
'use strict';
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
let SocketIO = NativeModules.SocketIO;
let SocketIOEventManager = new NativeEventEmitter(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 = SocketIOEventManager.addListener(
'socketEvent', this._handleEvent.bind(this)
);
// Set default handlers
this.defaultHandlers = {
connect: () => {
this.isConnected = true;
},
disconnect: () => {
this.isConnected = false;
}
};
if (Platform.OS === 'android') {
if(config.nsp) {
host = host + config.nsp;
delete config['nsp'];
}
if(config.connectParams) {
var str = Object.keys(config.connectParams).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(config.connectParams[key]);
}).join('&');
config['query'] = str;
}
}
// 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.handlers = {};
this.onAnyHandler = null;
this.sockets.disconnect();
}
reconnect () {
this.sockets.reconnect();
}
}
module.exports = Socket;