|
| 1 | +# @cjsx React.DOM |
| 2 | + |
| 3 | +@MessagesSection = React.createClass |
| 4 | + # Display name used for debugging |
| 5 | + displayName: 'MessagesSection' |
| 6 | + |
| 7 | + # Invoked before the component is mounted and provides the initial |
| 8 | + # state for the render method. |
| 9 | + getInitialState: -> |
| 10 | + # We'll change it to true once we fetch data |
| 11 | + didFetchData: false |
| 12 | + # The messages JSON array used to display the messages in the view |
| 13 | + messages: [] |
| 14 | + |
| 15 | + # Invoked right after the component renders |
| 16 | + componentDidMount: -> |
| 17 | + # Lets fetch all the messages... |
| 18 | + @_fetchMessages() |
| 19 | + setInterval(@_fetchMessages, 1000); |
| 20 | + |
| 21 | + # AJAX call to our MessagesController |
| 22 | + _fetchMessages: ()-> |
| 23 | + $.ajax |
| 24 | + url: Routes.messages_path() |
| 25 | + .done @_fetchDataDone |
| 26 | + .fail @_fetchDataFail |
| 27 | + |
| 28 | + # If the AJAX call is successful... |
| 29 | + _fetchDataDone: (data, textStatus, jqXHR) -> |
| 30 | + # We change the state of the component. This will cause the component and |
| 31 | + # it's children to render again |
| 32 | + @setState |
| 33 | + didFetchData: true |
| 34 | + messages: data |
| 35 | + |
| 36 | + # If errors in AJAX call... |
| 37 | + _fetchDataFail: (xhr, status, err) => |
| 38 | + console.error @props.url, status, err.toString() |
| 39 | + |
| 40 | + # How the component is going to be rendered to the user depending on it's |
| 41 | + # props and state... |
| 42 | + render: -> |
| 43 | + # The collection of Message components we are going to display |
| 44 | + # using the messages stored in the component's state |
| 45 | + messagesNode = @state.messages.map (message) -> |
| 46 | + # Message component with a data property containing all the JSON |
| 47 | + # attributes we are going to use to display it to the user |
| 48 | + <Message key={message.id} data={message}/> |
| 49 | + |
| 50 | + # HTML displayed if no messages found in it's state |
| 51 | + noDataNode = |
| 52 | + <div className="warning"> |
| 53 | + <h4>No messages found...</h4> |
| 54 | + </div> |
| 55 | + |
| 56 | + # Here starts the render result |
| 57 | + <div> |
| 58 | + <div className="messages-wrapper"> |
| 59 | + { |
| 60 | + # If there are messages render the messages... |
| 61 | + if @state.messages.length > 0 |
| 62 | + messagesNode |
| 63 | + # If has fetched data and no messages found, render the |
| 64 | + # warning message instead |
| 65 | + else if @state.didFetchData |
| 66 | + noDataNode |
| 67 | + } |
| 68 | + </div> |
| 69 | + </div> |
0 commit comments