Fully parse the Router routing in the Backbone. js framework of JavaScript and the javascript routing framework
The Router in Backbone acts as a route and controls the URL direction. It takes effect when the # tag is used in the URL.
Defining a Router requires at least one Router and one function to map a specific URL. Remember that in Backbone, any character after the # tag will be received and interpreted by the Router.
Next we will define a Router:
<Script> var AppRouter = Backbone. router. extend ({routes: {"* actions": "defaultRoute" // matching http://example.com/#anything-here}); // instantiate Router var app_router = new AppRouter; app_router.on ('route: defaultRoute ', function (actions) {alert (actions) ;}) // open the Backbone history. history. start (); </script>
Now we have defined a Router, but the Router does not match a specific URL. Next we will explain in detail how the Router works.
Dynamic Route Selection
Backbone allows you to define a Router with specific parameters. For example, you may want to receive a post through a specific id, such as a URL: "http://example.com/#/posts/12", once this Router is activated, you can get a post with id 12. Next, we will define this Router:
<Script> var AppRouter = Backbone. router. extend ({routes: {"posts/: id": "getPost", "* actions": "defaultRoute" // Backbone will match routes in sequence }}); // instantiate Router var app_router = new AppRouter; app_router.on ('route: getpost', function (id) {// note, the parameter is passed here alert ("Get post number" + id) ;}); app_router.on ('route: ulultroute ', function (actions) {alert (actions );}); // open the Backbone history. history. start (); </script>
Matching rules
Backbone uses two forms of variables to set the matching rules of the Router. The first one is: it can match any parameter between the slashes in the URL, and the other is *, which is used to match all the parts after the slashes. Note that because the ambiguity in the second form is greater than that in the first form, the matching priority is the lowest.
The results of any form of matching will be passed to the relevant function in the form of parameters. The first rule may return one or more parameters, and the second rule will return the entire matching result as a parameter.
Next, we will use an example to describe:
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 in the path user/images/hey.gif}); app_router.on ('route: loadview', function (route, action) {alert (route + "_" + action); // after matching, two parameters are passed. dashboard_graph} is displayed });
You may often hear the term "vro", but it often refers to a network device, which is a navigation and hub for network connection and data transmission. The "vro" function in Backbone is similar to it. From the above example, you can see that it can navigate different URL anchors to the corresponding Action method.
(Many Server Web frameworks also provide such a mechanism, but Backbone. Router focuses more on the navigation of front-end single-page applications .)
The routing and navigation of Backbone are completed by two classes: Backbone. Router and Backbone. History:
- The Router class is used to define and parse routing rules and map URLs to actions.
- The History class is used to listen for URL changes and trigger Action methods.
We generally do not directly instantiate a History, because when we create a Router instance for the first time, we will automatically create a History singleton object. You can access this object through Backbone. history.
To use the routing function, first define a Router class to declare the URL rules and actions to be listened to. In the preceding example, during the definition, we define the list of URLs to be listened to through the routes attribute. The Key indicates the URL rule, and the Value indicates the Action method executed when the URL is in the rule.
Hash rules
The URL rule indicates the Hash (Anchor) segment in the current URL. In addition to specifying a general string in the rule, we also need to pay attention to two special dynamic rules:
A string separated by a slash (/) in the rule. It is converted into an expression ([^ \/] +) in the Router class, indicating a slash) if: (colon) is set in this rule, the string in the URL will be passed to Action as a parameter.
For example, if the rule topic/: id is set, when the anchor is set to # topic/1023, 1023 will be passed to the Action as the parameter id. The parameter name (: id) in the rule) generally, the parameter name is the same as the parameter name of the Action method. Although the Router does not have such restrictions, it is easier to understand using the same parameter name.
* (Asterisk) in the rule will be converted into an expression (. *?) inside the Router (.*?), Represents zero or multiple arbitrary characters. Compared with the (colon) rule, * (asterisks) does not have the limit to separate/(diagonal lines, just like the * error rule defined in the preceding example.
The * (asterisk) rule in the Router uses the non-Greedy mode after it is converted to a regular expression. Therefore, you can use a combination rule like this: * type/: id, it can match # hot/1023 and pass hot and 1023 as parameters to the Action method.
The rule definition method is described above. All these rules 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. This method starts the URL listening. Inside the History object, the onhashchange event is used by default to listen for changes in the Hash (anchpoint) in the URL. For browsers that do not support the onhashchange event (such as IE6 ), history listens through the setInterval heartbeat method.
PushState rules
Backbone. history also supports URL in pushState mode. pushState is a new feature provided by html5. it can operate the URL of the current browser (instead of simply changing the anchor) without causing page refresh, this makes a single-page application more like a complete set of processes.
To use the pushState feature, you need to first understand some 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 object to the specified URL to the browser history.
2. replaceState (): This method can replace the current history object with the specified URL.
To call the pushState () and replaceState () methods, you only need to replace the URL of the current page and do not actually go to this URL address (when you use the back or forward button, will not jump to the URL), we can use the onpopstate event to listen to the URL changes caused by these two methods.
Routing Methods
1. route () method
After setting the routing rules, if you need to dynamically adjust the rules, 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 either a string or a regular expression: router. route (/^ topic /(. *?) /(.*?) $/, 'Page', function (pageno, pagesize) {// todo });
2. navigate () method
In the previous example, URL rules are triggered by manual input. In actual applications, you may need to manually jump to and navigate the URL rules.
Router. navigate () method for control, for example: router. navigate ('topic/123456', {trigger: true });
This code changes the URL to http: // localhost/index.html # topic/1000 and triggers the renderDetail method. Note that the trigger configuration is passed in the second parameter, which indicates whether to trigger the corresponding Action method while changing the URL.
3. stop () method
We still remember that we started the route listening through the Backbone. history. start () method. You can also call the Backbone. history. stop () method at any time to stop the listening. For example:
router.route('topic/:pageno/:pagesize', 'page', function(pageno, pagesize) { Backbone.history.stop(); });
Run this code and access URL: http: // localhost/index.html # topic/5/20. You will find that the listener no longer takes effect after this Action is executed.