Skip to content

Instantly share code, notes, and snippets.

@erikakers
Created December 5, 2013 20:56
Show Gist options
  • Save erikakers/7813742 to your computer and use it in GitHub Desktop.
Save erikakers/7813742 to your computer and use it in GitHub Desktop.
React Backbone
/**
* @jsx React.DOM
*/
var CommentModel = Backbone.Model.extend({
defaults: {
author: '',
text: '',
image: ''
}
});
var CommentsCollection = Backbone.Collection.extend({
model: CommentModel,
url: "/json/comments.json"
});
var BackboneMixin = {
componentDidMount: function() {
// Whenever there may be a change in the Backbone data, trigger a reconcile.
this.getBackboneModels().forEach(function(model) {
model.on('add change remove', this.forceUpdate.bind(this, null), this);
}, this);
},
componentWillUnmount: function() {
// Ensure that we clean up any dangling references when the component is
// destroyed.
this.getBackboneModels().forEach(function(model) {
model.off(null, null, this);
}, this);
}
};
var CommentBox = React.createClass({
mixins: [BackboneMixin],
componentDidMount: function() {
this.props.comments.fetch();
},
getBackboneModels: function() {
return [this.props.comments]
},
render: function() {
return (
<div className="comment-box">
<h2>Comments</h2>
<CommentList data={this.props.comments.models} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = _.map(this.props.data, function(comment){
return <Comment author={comment.get('author')} text={comment.get('text')} image={comment.get('image')}></Comment>;
});
return (
<div className="comment-list">
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render: function() {
return(
<div className="comment">
<h5 className="comment-author">
{this.props.author}
</h5>
<img className="comment-avatar" src={this.props.image} />
<p>{this.props.text}</p>
</div>
);
}
});
var CommentForm = React.createClass({
render: function() {
return (
<div className="comment-form">
I am a CommentForm.
</div>
);
}
});
React.renderComponent(
<CommentBox comments={new CommentsCollection()} />,
document.getElementById('content')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment