Search code examples
javascriptreactjsfrpbacon.js

Get EventStream from a node with React and Bacon


This is how I can get an EventStream from a regular DOM node with bacon.js:

var el = document.getElementById('input1');
var stream = Bacon.fromEvent(el, 'input')

When using React, DOM nodes may be recreated after some render() iteration, so obtaining events from real DOM nodes (with React.findDOMNode) is not an option. The only option I can think of for now is to handle events manually and then push them to buses:

var Component = React.createClass({
  streams: {},
  componentDidMount: function() {
    this.streams.inputBus = new Bacon.Bus();
  },
  componentWillUnmount: function() {
    this.streams.inputBus.end();
  },
  onInput: function(e) {
    this.streams.inputBus.push(e);
  },
  render: function() {
    return (
      <input type="text" onInput={this.onInput} />
    );
  }
});

Is this approach ok, or are there any better solutions?


Solution

  • I would say that it is OK. Similar approaches are used in these two examples: