首先说说发布订阅这种设计模式,这种模式我给它起了个别名叫遥控炸弹。很多朋友理解不了这种模式,那——
举个例子: 张三是个法外狂徒,它要去复仇,他想去炸掉仇家的房子。他来到仇家所在的小区,拿出自己准备的炸弹(监听)丢进仇家的屋里(页面),等他走出小区立马掏出遥控器(emit)按下爆炸按钮,复仇成功。
注意: 以上例子你可能会误解为炸弹只能爆炸一次,其实炸弹可以一直存在房子里,只要你不将他清理掉。所以张三完成复仇后,他应该去把炸弹清理掉,免得一直在屋子里,容易被警方发现。每个炸弹还应该有自己的名字(key),按爆炸开关的时候就可以精确引爆了。
export default class WSNetwork {
constructor(msgHandler) {
this.init();
this.msgHandler = msgHandler;
}
init() {
this.wssocket = null;
this.serverUrl = "ws://127.0.0.1:3000/websocket";
}
connect() {
this.wssocket = new WebSocket(this.serverUrl);
this.wssocket.onopen = this.onOpen.bind(this);
this.wssocket.onclose = this.onClose.bind(this);
this.wssocket.onerror = this.onError.bind(this);
this.wssocket.onmessage = this.onMessage.bind(this);
}
onOpen() {
console.log("WS_OPEN")
}
onClose() {
console.log("WS_CLOSE")
}
onError(e) {
console.log("WS_ERROR::", e)
}
onMessage(event) {
this.msgHandler(event);
}
}
const WS_LISTENER = 'WS_LISTENER'
export default class MessageProcess {
static httpCallbacks = {}
static msgListener = {}
static addMsgListener(serviceId, callBack) {
this.msgListener[serviceId] = callBack;
}
static emitData(msg) {
this.msgListener[WS_LISTENER](msg)
}
static msgHandler(msg) {
MessageProcess.emitData(msg)
}
static addHttpCallback(key, cbObj) {
MessageProcess.httpCallbacks[key] = cbObj
}
static initListener() {
MessageProcess.addMsgListener(WS_LISTENER, MessageProcess.onHttpCallBack)
}
static onHttpCallBack(msg) {
const key = msg.key
const callData = MessageProcess.httpCallbacks[key]
callData.callback(msg)
delete MessageProcess.httpCallbacks[key]
}
}
import WSNetwork from "./WSNetwork";
import MessageProcess from "./MsgProcess";
export default class NetManager {
static network = null
static msgId = 1
static initNetwork() {
NetManager.network = new WSNetwork();
MessageProcess.initListener();
}
static sendMsg(msg) {
return new Promise((resolve, reject) => {
NetManager.network.wsSendMsg(msg)
MessageProcess.addHttpCallback(NetManager.msgId++, {
callback: (data) => {
resolve(data)
}
})
})
}
}
|