Skip to content

Instantly share code, notes, and snippets.

@hden
Created August 6, 2015 17:56
Show Gist options
  • Save hden/9f4a90938b69daea378f to your computer and use it in GitHub Desktop.
Save hden/9f4a90938b69daea378f to your computer and use it in GitHub Desktop.
React JS Event-Emitter Mixin (you don't even have to inherent from React.Component)
import EventEmitter from 'events'
import shallowEqual from 'shallowEqual'
const shallowCompare = (instance, nextProps, nextState) => {
// https://github.com/facebook/react/blob/master/src/addons/shallowCompare.js
return (
!shallowEqual(instance.props, nextProps) ||
!shallowEqual(instance.state, nextState)
)
}
/*
* Usage
* class MyComponent extends Component {
* constructor(props, context, updater) {
* super(props, context, updater)
* this.on('componentWillReceiveProps', () => { console.log('Yay') })
* this.state = { foo: 'bar' }
* }
* render() {
* super.render()
* return (<div />)
* }
* }
*/
class Component extends EventEmitter {
constructor(props, context, updater) {
super()
this.props = props
this.context = context
this.refs = {}
this.updater = updater
}
setState(partialState = {}, callback) {
this.updater.enqueueSetState(this, partialState)
if (callback) {
this.updater.enqueueCallback(this, callback)
}
}
forceUpdate(callback) {
this.updater.enqueueForceUpdate(this)
if (callback) {
this.updater.enqueueCallback(this, callback)
}
}
render() {
this.emit('render', this)
}
componentWillMount() {
this.emit('componentWillMount', this)
}
componentDidMount() {
this.emit('componentDidMount', this)
}
componentWillReceiveProps(nextProps) {
this.emit('componentWillReceiveProps', this, nextProps)
}
shouldComponentUpdate(nextProps, nextState) {
this.emit('shouldComponentUpdate', this, nextProps, nextState)
return shallowCompare(this, nextProps, nextState)
}
componentWillUpdate(nextProps, nextState) {
this.emit('componentWillUpdate', this, nextProps, nextState)
}
componentDidUpdate(prevProps, prevState) {
this.emit('componentDidUpdate', this, prevProps, prevState)
}
componentWillUnmount() {
this.emit('componentWillUnmount', this)
this.removeAllListeners()
}
}
Copy link

ghost commented Aug 20, 2015

How to use it? For example when I have a Component which is consuming data like a list, and another component which is an editor and changes the data, how can I tell the list to update? thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment