Giter Site home page Giter Site logo

react-native-event-listeners's Introduction

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.)

Financial Contributors on Open Collective npm version dependencie status dev-dependency status npm npm travis build Coverage Status

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 easily the redux architecture for example.

Installation

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

or

yarn add react-native-event-listeners

Usage Example

Hint: The event listeners also work across different files. You only have to import the EventRegister in every file you need to send or receive your events.

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

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

react-native-event-listeners's People

Contributors

hhunaid avatar meinto avatar monkeywithacupcake avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-native-event-listeners's Issues

listener is called multiple times

In my case, the listener is called multiple times for each emit.

  useEffect(() => {
    const lst = EventRegister.addEventListener("nextprev", (data) => {
      tr("EventRegister.addEventListener " + data);
      if (data === "next") {
        handleSkipToNext();
      } else {
        handleSkipToPrevious();
      }
    });
    return () => {
      EventRegister.removeAllListeners();
    };

  }, []);

I emit like this:

<IconButton
  icon="skip-next"
  onPress={() => {
     EventRegister.emit("nextprev", "next");
  size={iconSize}
/>

Did I miss something?

removeAllListeners or removeEventListener doesn't change the count

Thank you for this awesome module.

Whenever I perform removeEventListener or removeAllListeners after registering a listener it does remove from ref array but count property remains unchanged. Why is that?

In addition to that, if I emit an event after removing the listener it still invokes the handler. Anything I'm missing here?

Listener never called

I am emitting an event in one Component like this...

EventRegister.emit(Constants.EVENT_REDEEMED_COUPON, json)

I have registered a listener like this...

componentWillMount(){
    this.listener = EventRegister.addEventListener(Constants.EVENT_REDEEMED_COUPON, (coupon) => {
            this.setState({
                coupon : coupon,
            })
            this.makeRemoteRequest();
        })
  }

When an event is emitted, the listener is never called.

How can I debug this?

Do we really need to remove listeners?

We are using this for token refresh. when token is refreshed an event is emitted. On IOS, we get a crash when phone is locked for a little while. Can you please advise why that is the case or is removing listeners really important?

Event listing being triggered twice

I have a simple popup component that I call using the event listener but the event listener is being called twice, I get two popups one on top of each other and I see two logs in the console. See below my code.

My listener component:

`
export const PopupModal = (props) => {
const [isModalVisible, setModalVisible] = useState(false)

const toggleModal = () => {
    setModalVisible(!isModalVisible);
};
const [msg, setMsg] = useState(() => {
    return {
        title: '',
        buttonText: '',
        message: ''
    }
})
useEffect(() => {
    const subscribe = EventRegister.addEventListener('showMsg', (data) => {
        setMsg(data)
        setModalVisible(true)

    })

    return () => {
        EventRegister.removeEventListener(subscribe)
    }
}, [])

return (
    <>
        {isModalVisible && <View style={{ flex: 1, position:'absolute' }}>
            <Modal coverScreen={true} isVisible={isModalVisible} >
                <View style={Styling.popupContainer}>
                    <Text style={Styling.popupTitle}>{msg.title}</Text>
                    <Text style={Styling.popupText}>{msg.message}</Text>
                    <View >
                        <TouchableOpacity style={Styling.popupTouchableOpacity} onPress={toggleModal} ><Text style={Styling.touchableOpacityTxt}>{msg.buttonText}</Text></TouchableOpacity>
                    </View>
                </View>
            </Modal>
        </View>}
    </>

);

}
`

its being triggered onPress like so
EventRegister.emit('showMsg', messagesService.popUpContactUsError)

Thanks in advance

Can not get listner in second class

Screenshot 2019-08-21 at 11 19 00 AM

I have to implement the same thing as per provided example but I can not get the argument in second class.

Bu t I can get console.log("@@@@@@", EventRegister._Listeners)

Not working on real device(Release mode)

Integrated this library for emitting events on an action and on other screen added some listeners to listen for the same events, which is working pretty fine as expected on simulator and device during debugging. But after release builds are generated for iOS and Android devices, its not working at all.

Anyone else has faced same issue?

Add TypeScript Types (.d.ts)

declare module "react-native-event-listeners" {
  class EventRegister {

    static addEventListener(eventName: string, callBack: () => void): string | boolean
    static removeEventListener(listenerRef: any): boolean
    static removeAllListeners(): boolean
    static emitEvent(eventName: string): void

    static on(eventName: string, callBack: () => void): string | boolean
    static rm(listenerRef: any): boolean
    static rmAll(): boolean
    static emit(eventName: string): void
  }
  export { EventRegister }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.