websocket前台js代码重构

来源:互联网 发布:数据割接流程 编辑:程序博客网 时间:2024/06/06 02:39

     websocket的前台页面代码书写,根据websocket的API,我们都很容易知道怎么写,就像前一篇websocket的实现过程中谈到的那样,onopen,onmessage等通过回调可以实现我们的目的,但是如果这样写,势必要我们在每个页面书写同样的代码,所以需要对websocket部分的js进行重构。但是问题来了,一旦重构这部分js代码,当然onmessage就应该写到js文件中,这样我们得到的实时数据就会产生在js文件,我们如何在html页面中获得实时数据呢?

       通过师兄的指点,看了一些js的知识和一些例子,觉得只应该用回调函数(也可以叫钩子)的办法解决这个问题。

       代码如下

js文件

 $.extend({     initWebSocket:function initWebSocket(s,method){       var url= $.URL.websocket.register;       ws = new WebSocket(url);       ws.onopen = function(){           setInterval(function(){$.post($.URL.user.keepAlive,null,null)},1000*60);           console.log("open"); ws.send(s);};       ws.onmessage=function (event){method(event.data);};       ws.onclose =function onclose(evt){console.log("WebSocketClosed!");};       ws.onerror =function onerror(evt){console.log("WebSocketError!");};    },     WebSocketClose:function WebSocketClose(){ws.close();ws=null},     WebSocketSend:function WebSocketSend(str){ws.send(str)},     WebSocketConnect:function WebSocketConnect(){return ws}});


html中的代码(只写websocket的调用部分)

     

 $.initWebSocket(s,webSocketCallback);

 function webSocketCallback(data){       //to do            }

这样我们就从js文件中拿到实时数据了

0 0