Before we finish this chapter, it's worth discussing how Views
interact with Routers
. Throughout this chapter, we've deliberately been vague about what you should actually do inside your routing functions, and part of the beauty of Backbone is that it leaves this decision entirely up to you.
For many Backbone users, however, a very common pattern is to create a special Page View
and then instantiate a different subclass of that View
in every route-handling method. Take an example of the following code snippet:
var Book = Backbone.Model.extend({urlRoot: '/book/'}); var Page = Backbone.View.extend({render: function() { var data = this.model ? this.model.toJSON() : {}; this.$el.html(this.template(data)); return this; } }); var BookPage = Page.extend({ template: 'Title: <%= title %>' }); var SiteRouter = new Backbone.Router({ route: { 'book/:bookId(/)': 'bookRoute', }, bookRoute: function(bookId) { var book = new Book({id: bookId}); book.fetch().done(function() { var page = new BookPage({model: book}); page.render(); }); } });
If your site has multiple sections, for instance a side navigation bar and a main content area, you can split up these parts into their own View
classes and then make those parts the defaults used by your Page View
class. You can then override these defaults as needed in your Page View
subclasses to allow these Views
to change the different parts of your site.
For instance, let's say most of the time, your site has a single side navigation bar but on certain pages, you wish to add some extra links to it. By using the Page View
architecture, such a scenario is easy to implement:
var StandardSidebar = Backbone.View.extend({ // Logic for rendering the standard sidebar });Page = Backbone.View.extend({ sideBarClass: StandardSidebar, render: function() { // render the base page HTML this.$el.html('<div id="sidebar"></div>' + '<div id="content"></div>'), // render the sidebar var sidebar = new this.sideBarClass({ el: this.$('#sidebar') }); sidebar.render(); // logic for rendering the content area would go here return this; } }); var AlternateSidebar = Backbone.View.extend({ // Logic for rendering the alternate sidebar }); var AlternateSidebarPage = Page.extend({ sidebarClass: AlternateSidebar });
As you can see in the preceding example, our AlternateSidebar
and AlternateSidebarPage
classes are very short. Thanks to the power of inheritance, they don't need to redefine any of your existing logic and can instead focus entirely on what makes them different: the logic for rendering the alternate sidebar. While your site may not even have a sidebar, it is no doubt made up of composable parts, and by breaking these parts into separate View
classes, your routes can simply use the appropriate class for whichever View
they wish to render.
3.133.138.134