I’m creating a TodoList example app using Flux. Right now I have three components: TodoListApp, TodoItems and AddItem. TodoListApp is simply a NavigatorIOS component which shows TodoItems by default and a method to push the AddItem page to the navigator stack when the user taps the ‘+’ button.
My question is: is there a way for my AddItem component (child of NavigatorIOS) to handle the onRightButtonPress event? Right now I’ve had to put in a bunch of hacks to accommodate adding a todo item when the user taps the ‘Save’ button from the AddItem page.
Currently the best way to do that is to create an
EventEmitter
in the owner of theNavigatorIOS
, then you can pass it down to children usingroute.passProps
. The child can mix inSubscribable.Mixin
and then incomponentDidMount
, you canthis.addListenerOn(this.props.events, 'myRightBtnEvent', this._handleRightBtnPress);
It is clear that this API needs improvement. We are actively working the routing API in Relay, and hopefully react-router, but we want NavigatorIOS to be usable independently. Maybe we should add an event emitter inside the
navigator
object, so child components can subscribe to various navigator activity:this.addListenerOn(this.props.navigator.events, 'rightButtonPress', this._handleRightBtnPress);
Feedback welcome!
@ericvicenti
Why not use
directly in the
componentDidMount
?What is
Subscribable.Mixin
‘s job here?@backslash112 Here is how I was able to have the “onRightButtonPress” trigger a function in the sub-component.
The only dependency I used is https://github.com/Olical/EventEmitter which can be added:
var EventEmitter = require('wolfy87-eventemitter');
In my main file (index.io.js) I created a new event emitter outside of the class:
var rightButtonHandler = new EventEmitter();
Then, inside the class I created a method to be called when the button is pressed:
handleSaveButton() { rightButtonHandler.emitEvent('saveButtonPressed'); }
And right below that I am passing the event emitter as a property to the sub-component:
passProps: { events: rightButtonHandler }
Now, switching to the sub-component class, add this or update your componentDidMount method:
componentDidMount() { this.props.events.addListener('saveButtonPressed', this.saveConcert.bind(this)); }
The above will be calling this saveConcert:
saveConcert() { /// This is now called when the navigatorIOS right button is pressed. }
Hope this helps!