https://github.com/mc-zone/react-event-emitter-mixin
Custom event utilities with lifecycle maintenance for React (both React and React-Native)
https://github.com/mc-zone/react-event-emitter-mixin
Last synced: 10 months ago
JSON representation
Custom event utilities with lifecycle maintenance for React (both React and React-Native)
- Host: GitHub
- URL: https://github.com/mc-zone/react-event-emitter-mixin
- Owner: mc-zone
- License: mit
- Created: 2015-10-05T10:51:57.000Z (almost 11 years ago)
- Default Branch: master
- Last Pushed: 2017-07-08T09:48:20.000Z (about 9 years ago)
- Last Synced: 2025-09-22T20:56:08.011Z (10 months ago)
- Language: JavaScript
- Homepage:
- Size: 11.7 KB
- Stars: 12
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-event-emitter-mixin [](https://travis-ci.org/mc-zone/react-event-emitter-mixin/) [](http://badge.fury.io/js/react-event-emitter-mixin)
Custom event utilities with lifecycle maintenance for React (Both React and React Native)
## Getting Started
Install via npm
```bash
npm i react-event-emitter-mixin --save
```
## Useage
Communicate between components under event emitter.
```javascript
var EventEmitterMixin = require('react-event-emitter-mixin');
var Child = React.createClass({
mixins:[EventEmitterMixin],
render(){
return (
{
this.eventEmitter('emit','eventA','foo','bar');
}}
>
press to emit event
);
}
});
var Parent = React.createClass({
mixins:[EventEmitterMixin],
componentWillMount(){
this.eventEmitter('on','eventA',(a,b)=>{
alert(a); //'foo'
alert(b); //'bar'
});
},
render(){
return (
);
}
});
```
Same usage when you are using ReactJs on Web.
## Lifecycle maintenance
Auto clean listeners when components be unmounted.
```javascript
var Child = React.createClass({
mixins:[EventEmitterMixin],
componentWillMount(){
this.eventEmitter('on','eventB',()=>{
alert('Will not show if `Child` was unmounted or not mounted')
});
this.eventEmitter('one','eventB',()=>{
alert('Once time per lifecycle')
});
},
render(){
//...
}
});
var Parent = React.createClass({
mixins:[EventEmitterMixin],
name:'parent',
getInitialState(){
return {
mountChild:true,
}
},
render(){
return (
{this.state.mountChild && (
)}
{
this.setState({mountChild:!this.state.mountChild})
}}
>
mount/unmount child
{
this.eventEmitter('emit','eventB');
}}
>
press to emit event
);
}
});
```
## API
```javascript
//Add event listener
this.eventEmitter('on', eventName:string, callback:function);
//Add once-only (per lifecycle) event listener
this.eventEmitter('one', eventName:string, callback:function);
//Remove event listeners which come from current component (or remove all)
this.eventEmitter('off', eventName:string, callback:function [,shouldRemoveAll:Boolean] );
//Emit event
this.eventEmitter('emit', eventName:string [,data1 [,data2,...] ] );
```
## LICENSE
MIT.
## Welcome PR :)