Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
by
Lessons:24Length:1.8 hours
Backbone
  • Overview
  • Transcript

5.1 Creating Routers

In this lesson we will begin discussing routers and backbone. The purpose of a router is to allow to create pages or states of your application. One of the issues of web applications that are front end heavy is that since there's no longer a need for the page to refresh, you can build an entire application that is hosted at a single URL, and so every single page has the same URL. Routers allow you to change that. They allow you to give different parts of your web application different routes. And that way, users will be able to say, bookmark different pages of our application. So in our application here, let's begin with a basic router class. I'm gonna create an AppRouter. And I'll be completely honest with you, you can really call your router whatever you want. Often, I'll just call mine Router, but AppRouter is good too. Now, you can actually, use multiple routers with your application if you want to divide the routes that you create, into different sets. And if that's the case, you may want to give it a more specific name. For example, I might call it BookRouter and let's go with that for now. Now just like all of our other Backbone components, we create a router by extending backbone.router. And of course you'll rarely have a router that has nothing inside of it. So, in the next lesson we're going to look at filling in this router. Instantiating a router, is as simple as saying new BookRouter for example. And just by instantiating a router, you have enabled it. So the next step after this would be to do Backbone.history.start. And go ahead and start up history. Starting with the history means that backbone will take note of route changes and this way you'll be able to move forward and backwards throughout your application using the router. Now if we just start up Backbone history like this, the routes that we create will use hash bangs. However, I would rather use push state, so we will pass an options object to start and say pushState equals true. And this way we can use push state routes. So this is the initial way to set up a router. In the next lesson we will look at creating specific routes.

Back to the top