-
-
Save c80609a/8dacbe35a53659814fa010b5b53ea010 to your computer and use it in GitHub Desktop.
React.js tutorial in coffeescript. http://facebook.github.io/react/docs/tutorial.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dom = React.DOM | |
CommentBox = React.createClass | |
getInitialState: -> | |
{data: []} | |
loadCommentsFromServer: -> | |
$.ajax | |
url: 'comments.json', | |
dataType: 'json', | |
success: (data) => | |
@setState {data: data} | |
error: (xhr, status, err) -> | |
console.error 'comments.json', status, err.toString() | |
handleCommentSubmit: (comment) -> | |
comments = @state.data | |
newComments = comments.concat [comment] | |
@setState {data: newComments} | |
$.ajax | |
url: @props.url | |
type: 'POST' | |
data: comment | |
success: (data) => | |
@setState {data: data} | |
componentWillMount: -> | |
@loadCommentsFromServer() | |
setInterval @loadCommentsFromServer, @props.pollInterval | |
render: -> | |
dom.div {className: 'commentBox'}, | |
dom.h1(null, 'Comments'), | |
CommentList({data: @state.data}), | |
CommentForm({onCommentSubmit: @handleCommentSubmit}) | |
CommentList = React.createClass | |
render: -> | |
commentNodes = @props.data.map (comment) -> | |
Comment {author: comment.author}, comment.text | |
dom.div {className: 'commentList'} | |
commentNodes | |
CommentForm = React.createCLass | |
handleSubmit: (ev) -> | |
author = @refs.author.getDOMNode().value.trim() | |
text = @refs.text.getDOMNode().value.trim() | |
@props.onCommentSubmit {author: author, text: text} | |
@refs.author.getDOMNode().value = '' | |
@refs.text.getDOMNode().value = '' | |
preventDefault ev | |
render: -> | |
dom.form {className: 'commentForm', onSubmit: @handleSubmit} | |
dom.input( | |
type: 'text' | |
placeholder: 'Your name' | |
ref: author | |
), | |
dom.input( | |
type: 'text' | |
placeholder: 'Say something fun !' | |
ref: text | |
), | |
dom.input( | |
type: 'submit' | |
value: 'Post' | |
) | |
Comment = React.createClass | |
render: -> | |
converter = new Showdown.converter() | |
rawMarkup = converter.makeHtml @props.children.toString() | |
dom.div {className: 'comment'}, | |
dom.h2({className: 'commentAuthor'}, | |
@props.author | |
), | |
dom.span({dangerouslySetInnerHTML: {__html: rawMarkup}}) | |
React.renderComponent | |
CommentBox({url: 'comments.json', pollInterval: 2000}), | |
document.getElementById('content') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment