JSFiddle - React, Tailwind, and code Playground

by timdouglas

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>tutorial</title>
    </head>
    <body>
    </body>
</html>

CSS

span.del, span.swap
{
    margin: 0 5px;
}

JavaScript

(function($) {

    Backbone.sync = function(method, model, success, error) {
        success(); //overrides persistant storage so we can use destroy() w/o error :S
    };

    var Item = Backbone.Model.extend({
        defaults: {
            part1: "hello",
            part2: "world"
        }
    });

    var List = Backbone.Collection.extend({
        model: Item
    });

    var ItemView = Backbone.View.extend({
        tagName: "li",
        events: {
            "click span.del": "remove",
            "click span.swap": "swap"
        },
        initialize: function() {
            _.bindAll(this, "render", "unrender", "remove", "swap");
            this.model.bind("change", this.render);
            this.model.bind("remove", this.unrender);
        },
        render: function() {
            $(this.el).html("<span>" + this.model.get("part1") + " " + this.model.get("part2") + "</span><span class='del'>[del]</span><span class='swap'>[swap]</span>");

            return this;
        },
        unrender: function() {
            $(this.el).remove();
        },
        swap: function() {
            var swapped = {
                part1: this.model.get("part2"),
                part2: this.model.get("part1")
            };
            this.model.set(swapped);
        },
        remove: function() {
            this.model.destroy();
        }
    });

    var ListView = Backbone.View.extend({
        el: $("body"),
        events: {
            "click button#add": "addItem"
        },
        initialize: function() {
            _.bindAll(this, "render", "addItem", "appendItem");

            this.collection = new List();
            this.collection.bind('add', this.appendItem); // collection event binder
            this.counter = 0;
            this.render();
        },
        render: function() {
            var self = this;

            $(this.el).append("<button id='add'>Add list item</button>");
            $(this.el).append("<ul></ul>");

           ...