Honest Actions in React (es6 + flux)
When using es6, some people like to auto-bind(autobinding) .bind(this) up in the class constructor for their action methods they’ll use later in the render() function, but I’ve been using the .bind() for my action/event handlers in a more explicit way.
When I need to grab some more info our from my elements, I used to attach some data on the element data attribute: data-behavior, and then later pick it out in my action handlers:
let behavior = e.currentTarget.dataset.behavior;
but, I realized you can inline data into the .bind() like .bind(this, behavior).
...{ behaviors.map( behavior =>
<a className="btn btn-info"
onClick={ this._editBehavior.bind(this, behavior) } >
Edit
</a>..._editBehavior(behavior, event) {
event.preventDefault();
Actions.updateBehavior(behavior);
}...
Very cool and clean ... so now I place .bind() on elements.
It’s more explicit and you have an honest action. You know what data you are exactly going to get from the handler.
Rather than using es7 syntax….
class Counter extends React.Component {
constructor() {
super();
this.tick = this.tick.bind(this);
}
tick() {
...
}
...
}
I’m not entirely sure how to bind methods to react component classes with es7 style syntax. One idea is to use the prototypal this in the action handler and drill down your props data or attach a ref on the element, but that would defeat the purpose.
All in all, explicitness trumps implicitness and being honest from the start will cause less problems later on like it is in life.
I will be adding this to the React Style Guide. Feel free to contribute :)
Happy 2016 New Years!