npm

Join us for the upcoming webinar, "Enterprise JavaScript done right: the tools you love, the security you need."Sign up here »

react-native-event-listeners

1.0.3 • Public • Published

React Native Event Listeners

(This package isn't only restricted to react-native projects. The source is written in plain js with no dependencies to react-native.)

npm version dependencie status dev-dependency status npm npm

Why

In some very specific cases it can be charming to have a simple global event listener. While working with global event listeners you don't have to pass touch events through the component tree into other components or can bypass easyly the redux architecture for example.

Installation

npm install --save react-native-event-listeners

or

yarn add react-native-event-listeners

Usage Example

import { EventRegister } from 'react-native-event-listeners'
 
/*
 * RECEIVER COMPONENT
 */
class Receiver extends PureComponent {
    constructor(props) {
        super(props)
        
        this.state = {
            data: 'no data',
        }
    }
    
    componentWillMount() {
        this.listener = EventRegister.addEventListener('myCustomEvent', (data) => {
            this.setState({
                data,
            })
        })
    }
    
    componentWillUnmount() {
        EventRegister.removeEventListener(this.listener)
    }
    
    render() {
        return <Text>{this.state.data}</Text>
    }
}
 
/*
 * SENDER COMPONENT
 */
const Sender = (props) => (
    <TouchableHighlight
        onPress={() => {
            EventRegister.emit('myCustomEvent', 'it works!!!')
        })
    ><Text>Send Event</Text></TouchableHighlight>
)

API

// import
import { EventRegister } from 'react-native-event-listeners'
static method return value description
addEventListener string | boolean return value is the id of the event listener or false on error
removeEventListener boolean true on success otherwise false
removeAllListeners boolean true on success otherwise false
emitEvent void no return value
on string | boolean shorthand for addEventListener
rm boolean shorthand for removeEventListener
rmAll boolean shorthand for removeAllListeners
emit void shorthand for emitEvent

install

npm i react-native-event-listeners

Downloadsweekly downloads

2,837

version

1.0.3

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability