Backbone + React Templates

by cesutherland

HTML

<script src="http://fb.me/react-0.5.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.5.0.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0-rc2/css/bootstrap.css">
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>

CSS

body {
    padding: 20px;
}

JavaScript 1.7

/** @jsx React.DOM */

function listTemplate (data) {
    var category = null;
    var list = data.products.reduce(function (list, product) {
        if (product.name.indexOf(data.query.filterText) === -1 || (!product.stocked & data.query.inStockOnly)) {
            return list;
        }
        if (product.category !== category) {
            category = product.category;
            list.push(
                <tr key={product.category}>
                    <th colSpan="2">{product.category}</th>
                </tr>
            );            
        }
        var name = product.stocked ?
            product.name :
            <span style={{color: 'red'}}>{product.name}</span>;
        list.push(
            <tr key={product.name}>
                <td>{name}</td>
                <td>{product.price}</td>
            </tr>
        );
        return list;
    }, [])
    return (
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>{list}</tbody>
        </table>
    );
}

function formTemplate (data) {
    return (
        <form>
            <input
                type="text"
                placeholder="Search..."
                value={data.filterText}
                onChange={this.handleInput}
            />
            <p>
                <input
                    type="checkbox"
                    value={data.inStockOnly}
                />
                Only show products in stock
            </p>
        </form>
    );
}

var ReactView = Backbone.View.extend({
    render: function() {
        React.renderComponent(this.template(this.data()), this.el);
        return this;
    }
});

var ListView = ReactView.extend({
    template: listTemplate,
    initialize: function () {
        this.listenTo(this.model, 'change', this.render);
    },
    data: function () {
        return {
            query: this.model.toJSON(),
  ...