Router in Backbone acts as a routing function, controlling the direction of the URL, and takes effect when using the # tag in the URL.
Defining a Router requires at least one Router and a function to map a specific URL, and we need to remember that in Backbone, any character after the # tag will be received and interpreted by the Router.
Let's define a Router:
<script> var AppRouter = Backbone.Router.extend({ routes: { "*actions": "defaultRoute" // Match http://example.com/#anything-here } }); // Instantiate Router var app_router = new AppRouter; app_router.on('route:defaultRoute', function(actions) { alert(actions); }) // Open Backbone's history Backbone.history.start();</script>Now, we have defined a Router, but at this time the Router does not match the specific URL. Next, we will start to explain in detail how Router works.
Dynamic routing
Backbone allows you to define a Router with specific parameters. For example, you might want to receive a post via a specific id, such as a URL: "http://example.com/#/posts/12". Once this Router is activated, you can get a post with an id of 12. Next, let's define this Router:
<script> var AppRouter = Backbone.Router.extend({ routes: { "posts/:id": "getPost", "*actions": "defaultRoute" //Backbone will match routes according to order} }); // Instantiate Router var app_router = new AppRouter; app_router.on('route:getPost', function (id) { // Note that the parameters are passed here alert( "Get post number " + id ); }); app_router.on('route:defaultRoute', function (actions) { alert( actions ); }); // Open Backbone's history Backbone.history.start();</script>Matching rules
Backbone uses two forms of variables to set the matching rules for Router. The first is:, which can match any parameters between slashes in the URL, and the other is *, which is used to match all parts behind the slashes. Note that since the second form has a greater ambiguity than the first, it has the lowest matching priority.
The result of any form of match is passed into the relevant function as a parameter. The first rule may return one or more parameters, and the second rule returns the entire match result as a parameter.
Next, let's use examples to illustrate:
routes:{ "posts/:id": "getPost", // <a href="http://example.com/#/posts/121">Example</a> "download/*path": "downloadFile", // <a href="http://example.com/#/download/user/images/hey.gif">Download</a> ":route/:action": "loadView", // <a href="http://example.com/#/dashboard/graph">Load Route/Action View</a>},app_router.on('route:getPost', function(id ){ alert(id); // After matching, the passed parameter is 12});app_router.on('route:downloadFile', function( path ){ alert(path); // After matching, the entire matching result is returned as a parameter, the path is user/images/hey.gif });app_router.on('route:loadView', function( route, action ){ alert(route + "_" + action); // After matching, two parameters are passed, dashboard_graph will pop up });You may often hear the word "router", but it often refers to a network device that is a navigation and hub for network connections, data transmission. The "router" function in Backbone is similar to it. As you can see from the above example, it can navigate different URL anchors to the corresponding Action method.
(This mechanism is also provided in many server-side web frameworks, but Backbone.Router focuses more on navigation of front-end single-page applications.)
Backbone's routing navigation is done by two classes Backbone.Router and Backbone.History:
We generally do not instantiate a History directly, because when we create a Router instance for the first time, we will automatically create a singleton object of History, which you can access through Backbone.history.
To use the routing function, we first need to define a Router class to declare the URL rules and Actions that need to be listened to. In the example just now, we define the URL list to be listened to through the routes attribute when defining, where Key represents the URL rules and Value represents the Action method executed when the URL is in this rule.
Hash rules
URL rules represent the Hash (anchor point) fragment in the current URL. In addition to being able to specify general strings in the rules, we also need to pay attention to two special dynamic rules:
A string separated by / (slash) in the rule will be converted into an expression ([^//]+) within the Router class, representing multiple characters starting with / (slash). If: (colon) is set in this rule, it means that this string in the URL will be passed to Action as a parameter.
For example, we set the rule topic/:id. When the anchor point is #topic/1023, 1023 will be passed to Action as parameter id. The parameter name (:id) in the rule will generally be the same as the formal parameter name of the Action method. Although Router does not have such restrictions, it is easier to understand using the same parameter name.
* (asterisk) in the rule is converted into an expression (.*?) inside the Router, representing zero or more arbitrary characters. Compared to the : (colon) rule, * (asterisk) has no / (slash) separation limitation, just like the *error rule we defined in the example above.
The * (asterisk) rule in Router uses a non-greedy pattern after being converted to a regular expression, so you can use a combination rule like this: *type/:id, which can match #hot/1023, and will pass hot and 1023 as parameters to the Action method.
The above introduces how rules are defined. These rules will correspond to an Action method name, which must be in a Router object.
After defining the Router class, we need to instantiate a Router object and call the start() method of the Backbone.history object, which will start listening to the URL. Inside the History object, the onhashchange event will be used to listen for changes in the URL to the Hash (anchor point). For browsers that do not support the onhashchange event (such as IE6), History will listen for the setInterval heartbeat.
pushState rules
Backbone.History also supports pushState URLs. pushState is a new feature provided by HTML5. It can operate the URL of the current browser (rather than just changing the anchor point), and will not cause page refresh, making a single page application more like a complete process.
To use the pushState feature, you need to first understand some of the methods and events provided by HTML5 for this feature (these methods are defined in the window.history object):
1.pushState(): This method can add a new history entity to the browser history to the specified URL.
2.replaceState(): This method can replace the current history entity with the specified URL
Calling pushState() and replaceState() methods is just to replace the URL of the current page, and it will not really go to this URL address (when using the back or forward button, it will not jump to the URL). We can listen to the URL changes caused by these two methods through the onpopstate event.
Routing related methods
1.route() method
After setting the routing rules, if dynamic adjustment is required, you can call the Router.route() method to dynamically add routing rules and Action methods, for example:
router.route('topic/:pageno/:pagesize', 'page', function(pageno, pagesize){ // todo }); When we call the route() method, the given rule can be not only a string, but also a regular expression: router.route(/^topic/(.*?)/(.*?)$/, 'page', function(pageno, pagesize){ // todo });2.navigate() method
In the previous example, URL rules are triggered by our manual input. In actual applications, it may sometimes be necessary to manually jump and navigation, and you can call it
Router.navigate() method is used for control, for example: router.navigate('topic/1000', { trigger: true });This code changes the URL to http://localhost/index.html#topic/1000 and triggers the renderDetail method. It should be noted that we pass in the trigger configuration in the second parameter, which is used to indicate whether the corresponding Action method is triggered while changing the URL.
3.stop() method
Remember we started routing listening through the Backbone.history.start() method. You can also call Backbone.history.stop() method at any time to stop listening, for example:
router.route('topic/:pageno/:pagesize', 'page', function(pageno, pagesize) { Backbone.history.stop(); });Run this code and access the URL: http://localhost/index.html#topic/5/20. You will find that after this Action is executed, the listening will no longer take effect.