Created
August 6, 2015 17:56
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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