Hierarchical Views with Backbone
http://programmingwithmosh.com/backbonejs/hierarchical-views-with-backbone/
by HYEONGJINKIM
HTML
<script src="//jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="//jashkenas.github.io/backbone/backbone-min.js"></script>
<div id="container">
<div id="masters" class="region"></div>
<div id="detail" class="region"></div>
</div>
CSS
.region {
width: 50%;
float: left;
border: 1px solid #ccc;
box-sizing: border-box;
padding: 30px;
}
JavaScript
// App
var App = App || {};
App.eventBus = _.extend({}, Backbone.Events);
// Models
App.Master = Backbone.Model.extend();
App.Masters = Backbone.Collection.extend({
Model: App.Master
});
// Views
App.MasterView = Backbone.View.extend({
events: {
"click": "onClick"
},
onClick: function(){
App.eventBus.trigger("master:select", this.model);
},
render: function(){
this.$el.html("<a href='#'>" + this.model.get("name") + "</a>");
return this;
}
});
App.MastersView = Backbone.View.extend({
render: function(){
this.collection.each(function(p){
var masterView = new App.MasterView({ model: p });
this.$el.append(masterView.render().$el);
}, this);
return this;
}
});
App.DetailView = Backbone.View.extend({
initialize: function(){
App.eventBus.on("master:select", this.onMasterSelected, this);
},
onMasterSelected: function(master){
this.model = master;
this.render();
},
render: function(){
if (!this.model) {
this.$el.html("Please select an item from the master list.");
} else {
this.$el.html(this.model.get("name"));
}
return this;
}
});
$(document).ready(function(){
var masters = new App.Masters([
new App.Master({ name: "Master 1" }),
new App.Master({ name: "Master 2" })
]);
var mastersView = new App.MastersView({ collection: masters });
$("#masters").html(mastersView.render().$el);
var detailView = new App.DetailView();
$("#detail").html(detailView.render().$el);
});