一个闭包,封装一些方法;(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事件
添加回答
举报
0/150
提交
取消