5 ms·
The way I'm integrating Backbone and React that is very simple and has been working well is something like this: MyComponent = React.createClass({
by hcarvalhoalves 12y ago
The way I'm integrating Backbone and React that is very simple and has been working well is something like this:
MyComponent = React.createClass({
componentDidMount: function(){
this.props.collection.on('request', function(){
this.setState({loading: true});
}.bind(this));
this.props.collection.on('sync', function(){
this.setState({loading: false});
}.bind(this));
this.props.collection.fetch();
},
});
Now you just write handlers to modify the collection and sync. setState takes care of triggering a render when your collection changes. As a bonus, you might want to render something different while in "loading" state.
If you don't want the component to own the collection (if you want to share a collection between multiple components), just pass it as a prop from a parent component; otherwise you can instantiate a new collection on getDefaultProps.
- wingspan 12y agoI believe the latest version of React does autobinding on component methods, so you shouldn't need .bind(this). There should be a warning letting you know this (unless it is different for the public version :/).
- vjeux 12y ago@wingspan: Facebook's runs the exact same code as the open source version, but on master.
- wingspan 12y agoAh right, I thought so. So as long as @hcarvalhoalves is using a recent version they should be fine.
- rattray 12y agoThanks! I find this very helpful. Seems like a terrific pattern.