2017-08-14 80 views
0

的JS模塊,我有一個被定義爲以下一個Websocket.JS:使用WebSocket.js在地方陣營組件

class Websocket extends Component { 

     constructor(props) { 
     super(props); 
     const url = Config.ws + Config.baseEndPoint + Config.pen; 
     const protocol = this.props.protocol; 
     const doesLogging = (this.props.doesLogging === "true"); 
     this.state = {"url": url, 
         "protocol": protocol, 
         "socket": new WebSocket(url, protocol), 
         "doesLogging": doesLogging}; 
     }; 

     onOpen() { 

     } 

     onMessage(msg) { 

     } 

     onClose() { 

     } 

     render() { 
     return (
      <div id="websocket"></div> 
     ); 
     } 

    } 

    export default Websocket; 

而且在app.js像這樣使用它:

import Websocket from './services/websocket'; 
    <Websocket handleMessage={(msg) => this.messageReceived(msg.data)} /> 

但是,我想將它作爲一個模塊使用,而不會像HTML元素那樣表示它。有沒有可能我可以做到這一點?

回答

0

我不認爲通過websockets進行的交互必須通過使用任何類型的UI庫來呈現在您的代碼中。因此:

class YourWebsocket{ 

     constructor(protocol, url, enableLogging) { 
     this.url = url; 
     this.protocol = protocol; 
     this.loggingEnabled = enableLogging; 
     this.socket = new WebSocket(url, protocol); 
     this.socket.onopen = (ev) => this.onOpen(); 
     // Assign more handlers here 
     } 

     onOpen() { 

     } 

     onMessage(msg) { 

     } 

     onClose() { 

     } 

     send(data, callback) 
     { 
     var listener = (e) => 
     { 
      var reply = e.data; 

      if(replyIsForOurRequest) //Here you should come up with the logic to decide if this is reply for your request 
      { 
       this.socket.removeEventListener("message", listener); 
       callback(reply);     
      } 
     }; 

     this.socket.addEventListener("message", listener); 
     this.socket.send(data); 
     } 
    } 

    export default YourWebsocket; 

而在你的app.js某處componentDidMount方法:

import YourWebsocket from './services/YourWebsocket'; 

class App extends React.Component 
{ 
    componentDidMount() 
    { 
     this.webSocket = new YourWebsocket(); 
     //... 
    } 
} 
+0

如何實例化這個在我app.js並將其耦合到處理器的功能呢?例如..回調在onMessage等情況下? – Salam

+0

實例在我的示例中已經出現,使用'componentDidMount'方法。發送功能 - 檢查我的更新。 – Amid

+0

如果我在componentDidMount()方法中實例化後定義處理程序,會不會有任何傷害?例如this.websocket.onmessage =(msg)=> {this.messageReceived(msg.data) }; – Salam