JSFiddle - React, Tailwind, and code Playground
by tsareg
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
JavaScript
// override default template settings to make templates look like templates in JRS
_.templateSettings = {
evaluate:/\{\{([\s\S]+?)\}\}/g,
interpolate:/\{\{=([\s\S]+?)\}\}/g,
escape:/\{\{-([\s\S]+?)\}\}/g
};
// in real world this data comes from server
var i18n = {
id: "ISBN",
title: "Title",
author: "Author"
};
var BookView = Backbone.View.extend({
el: "<tr>",
template: _.template(
"<td>{{- id }}</td>" +
"<td>{{- title }}</td>" +
"<td>{{- author }}</td>"),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var BookCollectionView = Backbone.View.extend({
// typically templates are loaded from separate template files
template: _.template(
"<table>" +
"<thead>" +
"<th>{{- i18n['id'] }}</th>" +
"<th>{{- i18n['title'] }}</th>" +
"<th>{{- i18n['author'] }}</th>" +
"</thead>" +
"<tbody>" +
"</tbody>" +
"</table>"),
initialize: function() {
this._subviews = [];
this.listenTo(this.collection, "reset", this.render);
this.listenTo(this.collection, "add", this.addSubview);
},
addSubview: function(model) {
var view = new BookView({ model: model });
this.$("tbody").append(view.render().$el);
this._subviews.push(view);
},
render: function() {
this.$el.html(this.template({ i18n: i18n }));
_.invoke(this._subviews, "remove");
this.collection.forEach(_.bind(this.addSubview, this));
return this;
},
remove: function() {
_.invoke(this._subviews, "remove");
Backbone.View.prototype.remove.apply(this, arguments);
}
});
// typically data comes from server, prefill it here for sample
var collection = new Backbone.Collection([
{
id: "978-1449328252",
title: "Developing Backbone.js Applications",
author: "Addy Osmani"
},
{
id:...