[StackOverflow] Organizing sub-views with backbone.js
http://stackoverflow.com/questions/8672705/organizing-sub-views-with-backbone-js/8674488
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
JavaScript
// Declare Basic Model wich have the render method
var Base = Backbone.Model.extend({
render: function () {
if (this.view) {
this.view.render();
}
}
});
// Declare Models
var Page = Base.extend({
initialize: function () {
// Add the view for this model
this.view = new PageView({ model: this });
}
});
var Book = Base.extend({
initialize: function () {
this.pages = new Pages(this.attributes.pages);
// Add the view for this model
this.view = new BookView({ model: this });
}
});
var BookShelf = Base.extend({
initialize: function () {
this.books = new Books(this.attributes.books);
// Add the view for this model
this.view = new BookshelfView({ model: this });
}
});
var BookstoreModel = Base.extend({
initialize: function () {
this.bookshelves = new Bookshelves(this.attributes.bookshelves);
this.view = new BookstoreView({ model: this });
}
});
// Declare Collections
var Pages = Backbone.Collection.extend({
model: Page
});
var Books = Backbone.Collection.extend({
model: Book
});
var Bookshelves = Backbone.Collection.extend({
model: BookShelf
});
// Views
var PageView = Backbone.View.extend({
render: function () {
console.log('Render page View : ' + this.model.attributes.content);
}
});
var BookView = Backbone.View.extend({
render: function () {
console.log('Render book View : ' + this.model.attributes.name);
}
});
var BookshelfView = Backbone.View.extend({
render: function () {
console.log('Render bookshelf View : ' + this.model.attributes.name);
}
});
var BookstoreView = Backbone.View.extend({
render: function () {
console.log('Render bookstore View');
}
});
// example of JSON data of the bookStore
var data = {
bookshelves: [{
id: 1,
name: 'Science',
books: [{
id: 1,
name: 'Abstract Algebra',
pages: [
...