nbjssdk
v1.0.0
Published
通用 JS 模块封装
Downloads
4
Readme
通用 JS 模块封装
通用的 JS 模块封装,支持所有 js 运行环境:web、微信小程序、react-native
功能
WebSocket
使用示例
const webSocketClient = new WebSocketClient(
{
uri,
},
window.WebSocket,
)
webSocketClient.traceFunction = data => console.debug('WebSocketClient', data)
webSocketClient.onConnected = reconnect => {
console.log('WebSocketClient', 'websocket连接成功, reconnect: ' + reconnect)
}
webSocketClient.onDisconnect = () => {
console.log('WebSocketClient', 'websocket连接已关闭')
}
webSocketClient.onMessage = msg => {
try {
const data = JSON.parse(msg)
console.log(data)
} catch (err) {}
}
webSocketClient.connect({
onFailure: data => {
console.log('WebSocketClient', 'websocket 连接失败:', data)
},
})
工具类
async-factory
异步工厂,用于生产单例对象,异步环境下可安全调用。
使用示例
class Connection {
constructor(options) {
this.options = options
}
}
const init = options => {
return new Promise(resolve => {
const conn = new Connection(options)
setTimeout(() => resolve(conn), 2000)
})
}
const asyncInitiator = asyncFactory(ConnectionManager.initConnection, 30 * 1000)
const sharedInstance = asyncInitiator(options)