Backbone.js Essentials by Jeremy Walker

Backbone.js Essentials by Jeremy Walker

Author:Jeremy Walker [Walker, Jeremy]
Language: eng
Format: epub
Tags: Web, Computers, Open Source, Programming Languages, JavaScript, Programming, Web Programming
ISBN: 9781784395322
Google: XZ-9CQAAQBAJ
Publisher: Packt Publishing Ltd
Published: 2015-05-29T21:08:53+00:00


Luckily, there are two alternatives that solve this problem: routing strings and regular expression routes. First, let's look at how regular expression routes can solve this problem:

SiteRouter = new Backbone.Router({ initialize: function(options) { // This regex will match "book/" followed by a number this.route(/^book\/(\d+)$/, 'bookRoute'); }, bookRoute: function(bookId) { // book route logic would go here } });

As you can see in the preceding example, we were able to create a single route with a regular expression that matches all our possible book routes. Because this expression contains a group (the part of the regular expression that is surrounded by parentheses), Backbone will pass the matching part of the route to the routing function as an argument, allowing us to know the book's ID from within our routing function. If we were to include multiple groups in our regular expression, Backbone would have provided each matching part of the route as a separate argument to our routing function.

Regular expressions are powerful, which makes them a good choice for defining routes. However, they have one major downside: they are hard for humans to read, especially when you revisit them months after writing them. As the old programming adage goes: you had a problem and tried to solve it using regular expressions. Now you have two problems. For this reason, Backbone provides a third option for defining routes: routing strings.

Routing strings are similar to regular expressions; in that, they let you define dynamic routes but are much more limited. You can only define groups (also known as parameters), wildcard groups (also known as splats), and optional parts. By trading away some of the power of regular expressions, routing strings gain a great deal of readability. Instead of using (\d+) to match a part of the route for a book's ID, a routing string will use the more readable bookId.

Just as with a regular expression route, Backbone will provide the route's parameters as arguments to the routing function, as shown here:

SiteRouter = new Backbone.Router({ initialize: function(options) { this.route('book/:bookId', 'bookRoute'); }, bookRoute: function(bookId) { // book route logic would go here } });



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.