I am trying to implement an EventEmitter/Subscriber relationship between two components in a react native class. I have seen referenced the following materials:
- React Native - Event Emitters by Colin Ramsay
- React Native - Call Function of child from NavigatorIOS
These solutions are adequate for what I am trying to accomplish, however, they bother require the use of mixins: [Subscribable.Mixin]
on the receiving component to work properly with Subscriber
. Unfortunately, I am using ES6 and extending my classes from Component
so I can not use this mixin syntax.
My question is: How can I implement the above solutions in ES6 without the use of mixins?
I was able to get a workaround with react-mixin. Not sure how proper it is, but it works without any modification. The key is adding
reactMixin(DetailView.prototype, Subscribable.Mixin);
after the class definition.Going off the example that is floating around for EventEmitter and Subscribable:
You don't need mixins to use EventEmitters.
Simple demo:
The full signature for
addListener
takes three args:In a react component, you likely want to use that context arg, so that the handler can be a class method instead of an inline function and still retain
this == component instance
. E.g.:FYI: I got this from looking at the decidedly unmagical implementation of the infamous Subscribable mixin. Google search results are basically an echo chamber of Ramsay's single mixin-based demo.
P.S. As far as exposing this emitter to another component, I'd probably have the owning component provide a function for receiving the emitter reference, and the component that creates the emitter would then conditionally execute that prop with the emitter.