Been searching for a while to see if there's anything built-in or any 3rd party modules for adding NSNotificationCenter style functionality to a react-native app.
Specifically, I want modules to "listen" for certain notification types, and I will be able to "broadcast" events from other parts of the app (from within javascript).
The closest thing I've found is this from 3 days ago: https://stackoverflow.com/a/32004456/798533, but it only supports sending NSNotificationCenter events, not listening.
Ok, I figured out an acceptable solution. Here's what I ended up doing in case anybody has the same question:
I installed the npm package backbone-events-standalone, which is just the extracted events code from Backbone.js.
In the main entry point for my app (index.ios.js
), I included the following code by the imports:
var BackboneEvents = require('backbone-events-standalone');
// global event bus
window.EventBus = BackboneEvents.mixin({});
Inside any component's componentDidMount
, you can now add event listeners, like so:
componentDidMount() {
window.EventBus.on('yourEventName', this.yourEventHandlerFunc);
}
And you can fire events thusly:
window.EventBus.trigger('yourEventName', 'optional event info');
This could also easily be combined with NSNotificationCenter events using something like the solution linked in the original question.
If you're removing components, it would be wise to also remove the event listeners, but I'll leave that as an exercise for the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With