title: React and websocket - data manipulation
body: <p>I am trying to implement communication with server through websocket.
  Let's say that I can't use Flux or similar libraries. My problem is updating data on server response.</p>
  
  <p>I am not sure how to implement callback functions on server response to update data.</p>
  
  <p>So far I have something like this(not an actual code)</p>
  
  <p><strong>events.js</strong></p>
  
  <pre><code>const e = require('event-emitter');
  var events = e();
  module.exports = events;
  </code></pre>
  
  <p><strong>socket.js</strong></p>
  
  <pre><code>const events = require('./events');
  
  module.exports = {
    var ws;
  
    init: function(URL) {
      ws = new WebSocket(URL);
      ws.onopen = function() { ... }
      ws.onclose = function() { ... }
      ws.onmessage = function(data) {
        events.emit(data.action, data);
      }
  
    },
  
    send: function(data) {
      ws.send(data);
    }
  }
  </code></pre>
  
  <p><strong>model.js</strong></p>
  
  <pre><code>const events = require('./events')
  var data = [];
  
  /* listening for some specific event from socket */
  events.on("action", doAction);
  
  function doAction(data) {
    events.push(data);
  
    /* now I have to emit event which react component
    is listening to so it can update data */
    events.emit("viewAction");
    }
  }
  
  /* what react component uses to get and render data */
  module.exports = {
    get: () =&gt; data,
    events: events
  }
  </code></pre>
  
  <p><strong>component.js</strong></p>
  
  <pre><code>const React = require('react');
  const ReactDOM = require('react-dom')
  const model = require('./model');
  
  var App = React.createClass({
    componentDidMount: function() {
      model.events.on('viewAction', this.refresh);
    },
  
    componentWillUnmount: function() {
      model.events.off('viewAction', this.refresh);
    }
  
    render: function() {
      return (
        &lt;div&gt;
          {model.get()}
        &lt;/div&gt;
      )
    }
  }
  
  ReactDOM.render(
    &lt;App /&gt;,
    document.getElementById('app')
  );
  </code></pre>
  
  <p>I hope sample makes it clear what I am trying to do and what my problem is. This also makes model event listener not work unless it is included in one of the react components which I am not too happy about.</p>
  
  <p>Is there a better way?</p>