Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of NSNotificationCenter for React Native?

Tags:

react-native

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.

like image 351
powers Avatar asked Aug 18 '15 04:08

powers


1 Answers

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.

like image 110
powers Avatar answered Oct 31 '22 13:10

powers