一個(gè)閉包,封裝一些方法;(function(window){varinitObj=null;varajaxSuccessResult='';vartimer=null;/***判斷是否支持websocket*@param*@returns{boolean}*/functionisSupported(){if(window.WebSocket&&(typeofWebSocket!='undefined')){returntrue;}returnfalse;}...太長(zhǎng),省略functionMSocket(options){if(!isSupported()){//polling獲取數(shù)據(jù)timer=setInterval(function(){ajax({url:options.http,data:options.ajaxData,type:options.type,})},3000);}else{returnnewWebSocket(options.http);}}//MSocket.prototype.onmessage=function(callback){////傳遞數(shù)據(jù),外面接收//callback(ajaxSuccessResult);//}//此處用websocket原生方法賦值給MSocket對(duì)象上;但是無(wú)效.MSocket.prototype.close=function(){returnWebSocket.close();};console.log(MSocket.prototype,'MSocket');if(typeofmodule!='undefined'&&module.exports){module.exports=MSocket;}elseif(typeofdefine=='function'&&define.amd){define(function(){returnMSocket;});}else{window.MSocket=MSocket;}}(window));vue中外部調(diào)用methods:{sendMessage(){this.socketCase.send(this.inputData);this.inputData='';},closeMessage(){//提示Cannotreadproperty'close'ofnull"this.socketCase.close();this.$toast('已關(guān)閉連接');},},mounted(){//實(shí)例化一個(gè)MSocket對(duì)象,傳入一些參數(shù)this.socketCase=newMSocket({ws:this.url,http:this.httpurl,ajaxData:{},type:'POST',...});//原生事件this.socketCase.onmessage=function(event){console.log(event,'onmessage');};//獲取到的window.WebSocket如下,所有的方法都掛在原型中。?WebSocket(){[nativecode]}我的疑問(wèn):即:如何在一個(gè)自定義對(duì)象上賦值原生WebSocket對(duì)象事件。比如實(shí)現(xiàn)監(jiān)聽(tīng)onmessage事件
小白,請(qǐng)教各位大佬!自定義對(duì)象上拷貝原生WebSocket對(duì)象的方法和事件謝謝哈~
手掌心
2019-12-02 08:04:31