MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Backbone.js: Router

This article covers how to use backbone router, an important part for your app so it can provide sharable, bookmarkable, and linkable URL. Youll also learn several methods provided by backbone to define function in route handling.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Today we are going to learn about backbone router, we are using backbone version 1.0.0. Router was previously called Controller before it got renamed on backbone version 0.5 for clarity. Okay, so what is a router?

Router is method for routing client side pages and connect them to events and actions via URLs. As we know, website as well as web applications running from browser, it commonly provides linkable, bookmarkable, sharable important URLs in the app. Specifically in web apps, so far web developers often use hash fragments (#pages) to achieve it. Now with the advent of History API, it's possible to use standard URL (/page) as in normal websites. For browser which doesn't yet support the History API, backbone router handle graceful fallback and transparent translation to fragment version of the URL. Let's start defining our first router.

Listing 1: Defining backbone router class

//define router class
var GalleryRouter = Backbone.Router.extend ({
	routes: {
		'' : 'home',
		'view': 'viewImage'
	},
	home: function () {
		alert('you are viewing home page');
	},
	viewImage: function () {
		alert('you are viewing an image');
	}
});

To define a new router class we extends from Backbone.Router and assign it to GalleryRouter. That's it, we just create a router class. But to make our router actually do something we have to map the routes. The routes hash maps URLs with parameters to methods on your router or simply a function declaration if you prefer.

In listing 1, we have only two routes, they are blank route ('') and view point to respective functions. Blank route means the URL doesn't have any parameter so we point it to home function, which in our example assuming to show the home page. And when a view parameter appears in URL (#view) we point it to viewImage method which can be used to show an image.

As I said instead of having routes pointing to respective methods, we can directly declare a function to each route, like this:

Listing 2: Directly declare function in routes hash

//define new router class
var GalleryRouter = Backbone.Router.extend ({
	routes: {
		'' : function () {
			alert('you are viewing home page');
		},
		'view': function () {
			alert('you are viewing an image');
		}
	}
});

Okay, so far we have defined our router class, but we need to make an instance in order to use router.

Listing 3: Instantiation of router

//define our new instance of router
var appRouter = new GalleryRouter();

// without History API 
Backbone.history.start(); 

//or

// use html5 History API
Backbone.history.start({pushState: true}); 

Everytime you use backbone router, don't forget about Backbone.history.start(). Your router will not work if it does not present since Backbone.history.start() will monitor hashChange event and dispatch routes

To get the advantage of History API, we do it like in the last line of listing 3 passing pushState in the option hash and set it to true. If you're testing pushState on local files, make sure put your files on local web server and call it via localhost otherwise you will get security error when navigating.

Now, assume that our app resides in http://localhost/galleryapp/index.html , everytime we enter in the browser address like this:

Viewing home page

Figure 1: Viewing home page

this will result alert saying 'you are viewing home page'.

and when we enter something like this and press enter:

Viewing an image

Figure 2: Viewing an image

this will alert 'you are viewing an image'.

Another way of defining our functions to handle route is using router.on() like this:

Listing 4: Router.on()

// define router class
	var GalleryRouter = Backbone.Router.extend({
		routes: {
			'' : 'home',
			'view': 'viewImage'
		}
	});
// define new router instance
	var appRouter = new GalleryRouter();

// using router.on()
	appRouter.on('route:home', function() {
		//code here
	});

	appRouter.on('route:viewImage', function() {
		//code here
	});

To use this method, first we have to make new router instance and assign it to a variable name like appRouter in above example. And from that instance, we listen to route using appRouter.on() passing route followed by colons and the function name we defined in routes hash of router class. And then define our function to handle the related route.

Router Parameters

In our example we have a 'view' route which lead to action viewing an image, but may be you notice this, what are we viewing? Which image we are viewing actually? Yes, our first example lacks of further information. This is when we can use route parameter, providing further information to certain routes represents an action like view or something else. See Listing Below

Listing 5: Router Parameters

// define router class
var GalleryRouter = Backbone.Router.extend({
	routes: {
		'': 'home',
		'view/:id' : 'view',
		'category/:name/p:page': 'showCategory'
	},
	home: function () {
		alert('you are viewing home page');
	},
	view: function (id) {
		alert('you are viewing an image with id of ' + id);
	},
	showCategory: function (name,page) {
		alert() 
	}
});

It's pretty simple to use router with parameter, after first action view we append a slash followed by colons and parameter's name. The parameter's name then will be available on the function which the route point to. This means in our example, we can use the parameter's name ( i.e 'id' ) inside the view methods. I will give you a pair example of URL matches to our example router:

- route: view/:id
example of matched URL fragment: '#view/7'

This route simply requires view as the first action and anything after view followed by slash in URL.

- route: category/:name/p:page
example of matched URL fragment: '#category/javascript/p31

This one is example of route with multiple parameters. It requires two parameters, name and page. The page parametes has a prefix, it looks like p:page will match p23, p34, anything starting with the prefix i.e p.

Optional Parameter

You can also ask for optional parameter in route by surrounding it in parenthesis (/:optional)

Listing 6: Optional router parameter

	…
	routes: {
		'category/:name(/:page)' : 'showCategory'			
	}
	… 

Above route will match these example of URL fragments:

'#category/javascript', or
'#category/javascript/9'

The first URL fragment has one action that is javascript, while in the second URL fragment, we pass javascript and an optional parameter (page). Whether you ignore or include 9 as the parameter, both of them are remain matched to route defined in listing 6.

Splat Parameter

Splat part (*splat) of parameters can match any number of URL components, it's like a wild card. This is useful to deal with un-handled route. For example you can define a default route as the last route to show an error or simply tell the user there is no such route. To use this parameter, simply start by appending an asterisk followed by parameter's name to the route.

Listing 7: Splat parameter

	…
	routes: {
		'file/*path': 'download',
		'*default': 'default'
	}
	… 

The file route above will match all of the following URLs:

  • '#file/ebooks/jsninja.zip'
  • '#file/media/picture.mpg'

And the second route will match all of these:

  • '#download/file/to/download'
  • '#remove/filename'

Router.navigate()

Use router.navigate() to update URL in your apps, you can navigate it from app view or from the router itself. This useful whenever you want to save your app as a URL or simply want to navigate from part to part on your app.

Listing 8: Router navigate

	var GalleryRouter = Backbone.View.extend({
		routes: {
			'view/:id': 'viewImage'
		},
		viewImage: function (id) {
			//code here
		}
	});
	//create new router instance
	var galleryRouter = new GalleryRouter();
	
	//use router.navigate()
	galleryRouter.navigate('view/19'); 
	//or
	galleryRouter.navigate('view/19', {trigger: true});
	//or
	galleryRouter.navigate('view/19', {trigger: true, replace: true});

Listing 8 shows how to use router.navigate, all of them will update the current URL. But the options hash makes each of them difference. The first case will only update the URL of you app, the second case will update the URL and call the route function (i.e viewImage function). The third case will do similar things to the second case, that is updating URL and calling viewImage function but it will not an entry in the browser's history.

Okay, if you're following my articles about backbone from the beginning, you should now be able to create your first complete backbone app. Hope you find this tutorial useful, see you.

Also read



A passionate and visionary web developer who falls in love with web technologies. Always excited to learn more, just like you.

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login