Backbone List-Detail View
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min.js"></script>
<!-- http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/ -->
<div id="app"></div>
<div id="detail"></div>
JavaScript
var AccommodationItem = Backbone.Model.extend({
defaults: {
html: "",
loaded: false
},
urlRoot: "/Home/Accommodation/"
});
var AccommodationItemView = Backbone.View.extend({
tagName: "li",
template: _.template("<a href='#accommodation/<%= id %>'><%= description %></a>"),
events: {
'click a': 'navigate'
},
navigate: function(e) {
e.preventDefault();
window.app.navigate('accommodation/' + this.model.id, true);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var AccommodationList = Backbone.Collection.extend({
model: AccommodationItem
});
var DetailView = Backbone.View.extend({
initialize: function() {
},
render: function() {
this.$el.html(this.model.get("html"));
},
setModel: function(model) {
this.model = model;
var $this = this;
if (!this.model.get("loaded")) {
/*
this.model.fetch({ success: function () {
$this.model.set("loaded", true);
$this.render();
}
});*/
$this.model.set("html", "<h2>Full item " + this.model.get("id") + "</h2>");
$this.model.set("loaded", true);
$this.render();
} else {
$this.render();
}
}
});
var AccommodationListView = Backbone.View.extend({
tagName: "ul",
initialize: function() {
this.collection.on("reset", this.render, this);
},
render: function() {
this.addAll();
},
addOne: function(item) {
var itemView = new AccommodationItemView({
model: item
});
this.$el.append(itemView.render().el);
},
addAll: function() {
this.collection.forEach(this.addOne, this);
}
});
var App = Backbone.Router.extend({
routes: {
"": "index",
"accommodation/:id": "show"
},
show: function(id) {
var model = window.appView.accommodationList.get(id);
window.appView.detailView.setModel(model);
}
});
var AppView = Backbone.View.extend({
initialize: function() {
this.detailView =...