Router Routing _ basics in the Backbone.js framework for full parsing of JavaScript

Source: Internet
Author: User
Tags extend

The Router in backbone acts as a route to control the direction of the URL and takes effect when using the # tag in the URL.
Defining Router requires at least one Router and one function to map a particular URL, and we need to remember that in backbone, any character after the # tag will be Router received and interpreted.
Here we 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 history record of the backbone
 Backbone.history.start ();
</script>

Now we've defined a Router, but at this point Router doesn't match a particular URL, so we'll start with a detailed explanation of how Router works.

Dynamic route Selection
backbone allows you to define Router with specific parameters. For example, you might want to receive a post with a specific ID, such as a URL: "HTTP://EXAMPLE.COM/#/POSTS/12", and once the Router is activated, you can get a post with ID 12. Next, we're going to define this Router:

<script>
 var approuter = Backbone.Router.extend ({
  routes: {"
   posts/:id": "Getpost",
   "*actions ":" Defaultroute "//backbone will match the route according to order
  }
 });
 Instantiate Router
 var app_router = new Approuter;
 App_router.on (' Route:getpost ', function (ID) {
  //note, the parameter is passed here with
  alert ("Get post number" + ID); 
 });
 app_router.on (' Route:defaultroute ', function (actions) {
  alert (actions); 
 });
 Open the history record of the backbone
 Backbone.history.start ();
</script>

Matching rules
Backbone uses two forms of variable to set the Router matching rule. The first is: it can match any argument between the slashes in the URL, and the other is *, which matches all the parts behind the slash. Note that because the second form of ambiguity is greater than the first, it has the lowest matching precedence.
The result of any match is passed in the form of a parameter to the related function, and the first rule may return one or more parameters, and the second rule returns the entire matching result as a parameter.
Next, we use an example to illustrate:

routes:{

 "Posts/:id": "Getpost",
 //<a href= "http://example.com/#/posts/121" >Example</a>

 "Download/*path": "DownloadFile",
 //<a href= "yun_qi_img/" >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);////match, pass over parameter to be
});
App_router.on (' Route:downloadfile ', function (path) { 
 alert (path);//match, the entire match is returned as a parameter, and the path is user/images/ Hey.gif 
});
App_router.on (' Route:loadview ', function (route, action) { 
 alert (route + "_" + action);///match, pass over two parameters, this will pop up DASHBO Ard_graph 
});

You may often hear of the word "router," but it often refers to a network device that is the network connection, the data transmission navigation and the hub. The "router" feature in backbone is similar to it, and you can see from the example above that it can navigate different URL anchors to the corresponding action method.
(This is also available in many server-side web frameworks, but backbone.router more focused on front-end Single-page application navigation.) )

Backbone routing navigation is done by Backbone.router and backbone.history two classes:

    • The router class is used to define and resolve routing rules and map URLs to action.
    • The history class is used to listen for changes to URLs and to trigger action methods.

We don't typically instantiate a history directly, because when we first create an router instance, we automatically create a history singleton object that you can access through backbone.history.

To use the routing feature, first we need to define a router class to declare the URL rules and action to be monitored, and in the example we defined, we define a list of URLs that need to be monitored by the routes attribute, where key represents the URL rule, Value represents the action method that is executed when the URL is in the rule.

Hash rule
The URL rule represents a hash (anchor) fragment in the current URL, and we need to note two special dynamic rules in addition to specifying a generic string in the rule:
A section of a string separated by/(slash) in a rule. Within the Router class, it is converted to an expression ([^\/]+), representing multiple characters beginning with a/(slash), which, if set in this rule: (a colon), indicates that the string in the URL will be passed as an argument to the action.
For example, we set the rule topic/:id, and when the anchor is #topic/1023, 1023 will be passed as the parameter ID to the action, and 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 limitations. But using the same parameter names is easier to understand.
The * (asterisk) in the rule is converted inside the router to an expression (. *?), which represents 0 or more arbitrary characters, and the * (asterisk) does not have the limit of/(slash) separation, as we have defined in the above example, as in the case of the (colon) rule *error.
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 matches #hot/1023, and passes hot and 1023 as arguments to the action method.

This describes how the rules are defined, which correspond to an action method name that must be in the Router object.
After defining the router class, we need to instantiate a router object and invoke the Backbone.history object's start () method, which initiates a listener for the URL. Inside the History object, the default is to listen for the hash (anchor) change in the URL through the Onhashchange event, and for browsers that do not support Onhashchange events (such as IE6), history will listen through the setinterval heartbeat.

Pushstate rules
Backbone.history also supports the pushstate approach of Url,pushstate is a new feature provided by HTML5, which operates the URL of the current browser (rather than just changing the anchor point) without causing the page to refresh, making it more like a complete process for a single page application to use. 。
To use the Pushstate feature, you need to understand some of the methods and events that HTML5 provides for the attribute (these methods are defined in the Window.history object):

1.pushState (): This method can add a new history entity to the browser history with the specified URL
2.replaceState (): This method can replace the current history entity with the specified URL

The Pushstate () and Replacestate () methods are invoked simply to replace the URL of the current page without actually going to the URL address (and will not jump to the URL when using the back or Forward button). We can listen to the URL changes caused by these two methods by Onpopstate events.

Routing related Methods

1.route () method
after you set the routing rules, if you need to adjust dynamically, you can invoke the Router.route () method to dynamically add routing rules and action methods, for example:

Router.route (' topic/:p ageno/:p agesize ', ' 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, the URL rules are triggered by our manual input, in practical applications, sometimes may need to manually jump, navigation, you can call

The Router.navigate () method controls, 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. Note that we passed the trigger configuration in the second argument, which is used to indicate whether the corresponding action method is triggered when the URL is changed.

3.stop () method
Remember that we are using the Backbone.history.start () method to start the routing listener, you can also call the Backbone.history.stop () method at any time to stop listening, for example:

Router.route (' topic/:p ageno/:p agesize ', ' page ', function (PageNo, pagesize) { 
 Backbone.history.stop (); 
}); 

Run this code and visit Url:http://localhost/index.html#topic/5/20, and you will find that the action is executed and the listener is no longer in effect.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.