react-listento

mixin for React.js that provide easy event binding

Usage no npm install needed!

<script type="module">
  import reactListento from 'https://cdn.skypack.dev/react-listento';
</script>

README

React-listenTo

react-listenTo is a React mixin that provides:

  • listenTo(emitter, eventName, cb) method to your component
  • noListenTo(emitter, [eventName , [cb]] method to your component
  • automatically unbind all event listener when the component unmount

Usage

With listenTo() we can break down the React's props passing chain smaller. This help us structure the components easier.

var video = require('video-player');
var listenTo = require('react-listenTo');

var FastForwardButton = React.createClass({
    mixins: [listenTo],

    componentDidMount: function() {
        this.listenTo(video, 'playbackRate', this.updatePlaybackRate);
    },

    updatePlaybackRate: function(val) {
        this.setState({playbackRate: val});
    },

    render: function() {...}
});

Under the hood

listenTo tries its best work with all the common event emmitters. When listen to events from an emmiter, the method will try and guess for common listening API: [on, attachEvent, addEventListener].

DOM element
node EventEmitter
backbone Model and Collection
...

The same idea applies for noListenTo method.

When component unmount, it will also automatically call noListenTo to all event handlers attached through listenTo. So external event emmitter will not keep reference to yours anymore.