JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<html>
<head>
<meta charset="utf-8">
<title>hello-backbonejs</title>
</head>
<body>
</body>
</html>
JavaScript
(function($) {
Backbone.sync = function(method, model, success, error) {
success();
};
var Item = Backbone.Model.extend({
defaults: {
part1: 'Hello',
part2: 'World'
}
});
var List = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li',
initialize: function() {
_.bindAll(this, 'render', 'unrender', 'swap', 'remove');
this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);
},
events: {
'click span.swap': 'swap',
'click span.delete': 'remove'
},
render: function() {
$(this.el).html('<span style="color:black;">' + this.model.get('part1') + ' ' + this.model.get('part2') + '</span> <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</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);
this.counter = 0;
this.render();
},
render: function() {
$(this.el).append("<button id='add'>Add list item</button>");
...