Skip to content

Instantly share code, notes, and snippets.

@tutuca
Last active August 29, 2015 14:27
Show Gist options
  • Save tutuca/4f77a6d1b3d08e7a1997 to your computer and use it in GitHub Desktop.
Save tutuca/4f77a6d1b3d08e7a1997 to your computer and use it in GitHub Desktop.
A mixin for ReactJS that looks for `this.props.collection` or `this.props.model` listens for all Backbone events to update the React Component.
define([
], function() {
return {
componentDidMount: function() {
this._boundForceUpdate = this.forceUpdate.bind(this, null);
this.getBackboneObject().on("all", this._boundForceUpdate, this);
},
componentWillUnmount: function() {
this.getBackboneObject().off("all", this._boundForceUpdate);
},
getBackboneObject: function() {
return this.props.collection || this.props.model;
}
};
});
/** @jsx React.DOM */
define([
"Backbone",
"React",
"ListComponent"
], function(React, ListComponent) {
var ListItem = Backbone.Model.extend({});
var ListItemCollection = Backbone.Collection.extend({
model: ListItem
});
var listItemCollection = new ListItemCollection();
React.renderComponent(
<ListComponent collection={listItemCollection} />,
document.body
);
listItemCollection.set([
new ListItem(),
new ListItem(),
new ListItem()
]);
});
/** @jsx React.DOM */
define([
"React",
"BackboneMixin"
], function(React, BackboneMixin) {
return React.createClass({
mixins: [BackboneMixin],
render: function() {
var listItems = this.props.collection.map(function(model) {
return (<li key={model.cid}>{model.cid}</li>);
});
return (
<ul>
{listItems}
</ul>
);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment