websocket怎样在其他場景的组件里調用onmessage?賦給全局變量cc.ws後到另一場景后变null了…
全局变量是window
也用過了,轉場景後也獲取不到前一場景的websocket
找到了!
// ws模块:
const WS = {
ws: null,
wsUrl: null,
_setWsCloseFunc: function () {},
_setOpenFunc: function () {},
_setMessageFunc: function () {}
}
// 连接websocket
WS._createWebSocket = function (url) {
try {
this.ws = new WebSocket(url)
this._initEventHandle()
}
catch (e) {
console.log(‘catch’, e)
}
}
// websocket事件
WS._initEventHandle = function () {
this.ws.onclose = () => {
this._setWsCloseFunc()
}
this.ws.onerror = (err) => {
}
this.ws.onopen = () => {
this._setOpenFunc()
}
this.ws.onmessage = (event) => {
this._setMessageFunc()
}
}
module.exports = WS
// 游戏逻辑模块
import WS from ‘./ws’
cc.Class({
extends: cc.Component,
properties: {
},
onLoad () {
},
start () {
WS._setOpenFunc = this._setOpenFunc.bind(this)
WS._setMessageFunc = this._setMessageFunc.bind(this)
WS._setWsCloseFunc = this._setWsCloseFunc.bind(this)
},
// onclose
_setWsCloseFunc () {
},
// onopen
_setOpenFunc () {
},
// onmessage
_setMessageFunc () {
},
})
作者:xurna
链接:https://www.jianshu.com/p/3a59fed4bbf7
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
谢大佬,我也在找