JSFiddle - React, Tailwind, and code Playground

by BrianGenisio

HTML

<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<div id="creaturesView">
    <div>
        <input type="text" id="name" hint="creature name" />
        <button id="add">Add one</button>
    </div>
    
    <ul id="list"></ul>
</div>

JavaScript

// This prefilter is necessary to maintain a session with CORS
$.ajaxPrefilter( function(options) {
  options.xhrFields = { withCredentials: true };
});


var Creature = Backbone.Model.extend({});
var Creatures = Backbone.Collection.extend({
    model: Creature,
    url: "http://localhost:3000/creatures"                
});

var CreatureView = Backbone.View.extend({
    tagName: "li",
    template: _.template("Creature: <%= name %>  <a href='#' class='remove'>&times;</a>"),
    
    events: {
        "click .remove": "removeItem"
    },
    
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },
    
    removeItem: function() {
        this.model.destroy();            
    }
});

var CreaturesView = Backbone.View.extend({
    events: {
        "click #add": "addItem"
    },
    
    initialize: function() {
        _.bindAll(this, "render", "renderItem");
        this.model.on("reset", this.render);
        this.model.on("add", this.renderItem); 
        this.model.on("remove", this.render);        
    },
    
    render: function() {
        this.$("#list").html("");
        this.model.each(this.renderItem);        
        return this;         
    },
    
    renderItem: function(item) {
        var itemView = new CreatureView({model: item});
        this.$("#list").append(itemView.render().el);            
    },
    
    addItem: function() {
        this.model.create({name: this.$("#name").val()});
    }
});

var creatures = new Creatures();
var creaturesView = new CreaturesView({el: $("#creaturesView"), model: creatures});

creatures.fetch();