JSFiddle - React, Tailwind, and code Playground
by knunery
HTML
<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>
<div class='liveExample'>
<h2>People</h2>
<div id="people_container"></div>
</div>
CSS
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }
.renderTime { color: #777; font-style: italic; font-size: 0.8em; }
li { list-style-type: disc; margin-left: 20px; }
JavaScript
//Collections
var PersonModel = Backbone.Model.extend({
initialize: function() {
console.log('initialize');
},
defaults: {
name: "notset",
children: [],
numChildren: 0
},
addChild: function(childName) {
this.children.add(childName);
}
});
var PeopleList = Backbone.Collection.extend({
model: PersonModel
});
var PersonView = Backbone.View.extend({
events: {
"click a": "addChild"
},
template: _.template("<div><%= name %> has <%= children.length %> children <a href='#'>Add child</a></div><ul><% _.each(children, function(name) { %><li><%= name%></li><%});%></ul>"),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
},
addChild: function() {
var children = this.model.get('children');
children.push('new child');
this.render();
}
});
var PeopleView = Backbone.View.extend({
initialize: function() {
this.render();
},
el: $('#people_container'),
render: function() {
console.log('PeopleView :: render');
this.collection.forEach(this.addOne, this);
},
addOne: function(model) {
var personView = new PersonView({
model: model
});
personView.render();
this.$el.append(personView.el);
},
});
var allPeople = [
new PersonModel({
name: "Annabelle",
children: ["Arnie", "Anders", "Apple"]
}),
new PersonModel({
name: "Bertie",
children: ["Boutros-Boutros", "Brianna", "Barbie", "Bee-bop"]
}),
new PersonModel({
name: "Charles",
children: ["Cayenne", "Cleopatra"]
}),
];
var peopleView = new PeopleView({
collection: allPeople
});
/*
//Knockout
// Define a "Person" class that tracks its own name and children, and has a method to add a new child
var Person = function(name, children) {
this.name = name;
this.children = ko.observableArray(children);
this.addChild = function() {
...