一個閉包,封裝一些方法;(function(window){varinitObj=null;varajaxSuccessResult='';vartimer=null;/***判斷是否支持websocket*@param*@returns{boolean}*/functionisSupported(){if(window.WebSocket&&(typeofWebSocket!='undefined')){returntrue;}returnfalse;}...太長,省略functionMSocket(options){if(!isSupported()){//polling獲取數據timer=setInterval(function(){ajax({url:options.http,data:options.ajaxData,type:options.type,})},3000);}else{returnnewWebSocket(options.http);}}//MSocket.prototype.onmessage=function(callback){////傳遞數據,外面接收//callback(ajaxSuccessResult);//}//此處用websocket原生方法賦值給MSocket對象上;但是無效.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中外部調用methods:{sendMessage(){this.socketCase.send(this.inputData);this.inputData='';},closeMessage(){//提示Cannotreadproperty'close'ofnull"this.socketCase.close();this.$toast('已關閉連接');},},mounted(){//實例化一個MSocket對象,傳入一些參數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]}我的疑問:即:如何在一個自定義對象上賦值原生WebSocket對象事件。比如實現監聽onmessage事件
小白,請教各位大佬!自定義對象上拷貝原生WebSocket對象的方法和事件謝謝哈~
手掌心
2019-12-02 08:04:31