Backbone.js Series Tutorials Seven: Backbone.router

Source: Internet
Author: User
Tags define extend hash log query regular expression string window

Backbone.router () overview

A backbone route is a JavaScript string, similar to the URL path name in traditional knowledge. This string-like pathname is the property name (or reference-named function) of a function that is invoked when a URL in the browser matches a string. For example, the URL in the following example contains the pathname "help", which, in a separate backbone application page, calls a function that associates a route named ' Help. ' Backbone

http://www.hostname.com/#help

Note that the pathname "help" is not actually a path name, but a hash. Backbone uses a hash path by default because it is now considered the most widely supported solution for creating unique URL strings without causing the browser to reload. You no longer need to support IE9 or the following version to allow backbone to use the latest HTML5 history.pushstate, which eliminates the need to use a hash path. The History.pushstate API updates the browser and allows you to modify the path name of the URL without causing the browser to reload. I'll discuss this in more detail later in this section. Now, let's look at a backbone route instance. In the following code, I created the default backbone.router () instance and then used the route () method to define a "help" route.

 
  
  
  1. //Show page load time URL appearance
  2. $ ("#urlPL span"). Text (window.location.href);
  3.  
  4. //create a backbone Router
  5. var myrouter = new Backbone.router ();
  6.  
  7. //let backbone start listening for changes on the URL
  8. backbone.history.start ();
  9.  
  10. //uses the routing method to create a help route, route (route, name, Callback-function)
  11. myrouter.route (' help ', ' Help ', function () {
  12. Console.log ("The URL hash just change to /#help ");
  13.  
  14. //to change the URL hash to "#help"
  15. window.location.hash = "help";
  16.  
  17. //show the appearance of the URL after the hash code, note the #help
  18. $ ("#url span"). Text (window.location.href);

In the preceding code example, when the hash changes to #help,backbone can receive the change and all the content behind the # and match it to a predefined string name (that is, "help"), and is associated with a callback function.

A route is a basic pathname of a URL string, which is monitored by a backbone string match, and a corresponding function is invoked after the match succeeds.

Tips:

    • Routing is used by default on a URL in the Hashchange event and in the hash section. If backbone is configured to use History.pushstate () and the Popstate event and the normal pathname are available, they are used, and if they are not available, the hash is returned by default. If the backbone detection result is that none of these events is available, a polling (polling) URL will be taken to monitor whether it has been altered.

Using Backbone.history.start () to start routing management

In order for backbone to start managing URL changes (including calling default routes, listening to routing, managing browser history, and processing return buttons), you need to invoke Backbone.history.start (). A detailed description of this method can be found in the Backbone.history section. Now, just know that backbone has to manually tell the browser to start the routing process. In the following code, I created a "help" route, but backbone hasn't started listening to URL changes until Backbone.history.start () is invoked.

 
  
  
  1. Create a backbone Router
  2. var myrouter = new Backbone.router ();
  3. Create a help route using the routing method, route (route, name, Callback-function)
  4. Myrouter.route (' Help ', ' Help ', function () {
  5. Console.log ("The URL hash just change to/#help");
  6. });
  7. Change the URL hash to "#help", but backbone does not change
  8. Window.location.hash = "Help";
  9. Let backbone start listening for changes on the URL
  10. Backbone.history.start ();
  11. Change the URL hash to "#help", and now the route is ready to work!
  12. Window.location.hash = "Help";

Backbone initial route

The initial route is run when the Backbone.history.start () is invoked. Defining an initialization route is to send an empty string route name to this route, indicating that the route was run by default at the start of the route. In the following code, I define an initialization route that is invoked when Backbone.history.start () is invoked.

 
  
  
  1. Create a backbone Router
  2. var myrouter = new Backbone.router ();
  3. Create an initial route
  4. Myrouter.route ("", "Initialroute", function () {
  5. Console.log ("The intital route has been invoked");
  6. });
  7. Let backbone start listening for changes on the URL, run the initial route
  8. Backbone.history.start ();
  9. Show URL Appearance:
  10. $ ("#url span"). Text (window.location.href);

Tips:

    • Starts the route without invoking the initialization path, passing the {silence:true} to the. Start () method.

Defining routes

This step demonstrates the use of the route () method to define a route after the Backbone.router () instance is instantiated. In simple terms, defining a route is done not just through the route () method, but also through the following four methods (including the route () method):

1: When you inherit backbone.router with the routes option

 
  
  
  1. Inherit Backbone.router ()
  2. var extendedrouter = Backbone.Router.extend ({
  3. Routes: {
  4. ' Help ': ' Help '
  5. },
  6. Help:function () {
  7. Console.log ("The URL hash just change to/#help");
  8. }
  9. });
  10. Create a backbone Router
  11. var myrouter = new Extendedrouter ();
  12. Let backbone start listening for changes on the URL
  13. Backbone.history.start ();
  14. Change the URL hash to "#help"
  15. Window.location.hash = "Help";

2: When instantiating a route with the routes option:

 
  
  
  1. Create a backbone Router
  2. var myrouter = new Backbone.router ({
  3. Routes: {
  4. "Help": function () {
  5. Console.log ("The URL hash just change to/#help");
  6. }
  7. }
  8. });
  9. Let backbone start listening for changes on the URL
  10. Backbone.history.start ();
  11. Change the URL hash to "#help"
  12. Window.location.hash = "Help";

3: After you create an instance using the route () method:

 
  
  
  1. Create a backbone Router
  2. var myrouter = new Backbone.router ();
  3. Let backbone start listening for changes on the URL
  4. Backbone.history.start ();
  5. Create a help route using the route method, route (route, name, Callback-function)
  6. Myrouter.route (' Help ', ' Help ', function () {
  7. Console.log ("The URL hash just change to/#help");
  8. });
  9. Change the URL hash to "#help"
  10. Window.location.hash = "Help";

4: During initialization of an instance with the route () method:

 
  
  
  1. var extendedrouter = Backbone.Router.extend ({
  2. Initialize:function () {
  3. This.route ("Help", "help"); Seek this.help (ie Myrouter[help])
  4. },
  5. Help:function () {//will become an instance property
  6. Console.log ("The URL hash just change to/#help");
  7. }
  8. });
  9. Create a backbone Router
  10. var myrouter = new Extendedrouter ();
  11. Let backbone start listening for changes on the URL
  12. Backbone.history.start ();
  13. Change the URL hash to "#help"
  14. Window.location.hash = "Help";

The above code you can run it yourself.

Run a route with a wildcard pathname (also called splats or *)

A wildcard path name can be used in any pathname to run the path. For example, once a URL changes, routing "*anyurl" will be run.

 
  
  
  1. var myrouter = new Backbone.router ();
  2. Backbone.history.start ();
  3. Myrouter.route ("*anyurl", "Anyurl", function () {
  4. Console.log ("called Anytime the URL changes to any URL path");
  5. });
  6. Change the URL hash to "#foo"
  7. Window.location.hash = "Foo";
  8. Change the URL hash to "#foo/boo/bar?coo=too&noo=loo"
  9. settimeout (function () {Window.location.hash = "QA";},2000);

Once the URL is changed to "Help/anything/anything", the route "/help/*" runs.

 
  
  
  1. var myrouter = new Backbone.router ();
  2. Backbone.history.start ();
  3. Myrouter.route ("Help/*anyurl", "Anyurl", function () {
  4. Console.log ("called Anytime the URL changes to any URL path");
  5. });
  6. Change the URL hash to "#foo"
  7. Window.location.hash = "Help/foo";
  8. Change the URL hash to "#/help/foo/boo/bar?coo=too&noo=loo"
  9. settimeout (function () {Window.location.hash = "Help/foo/boo/bar?coo=too&noo=loo";},2000);

Tips:

    • Passing a single splat route (that is, "*") can cause backbone to throw an error

Passing parameters from a URL to a routing callback function

In order to define the URL part, you should place a ': ' before the parameter name in the route string. For example, in the following code, I passed 4 parameters to the search routing callback function.

 
  
  
  1. var myrouter = new Backbone.router ();
  2. Backbone.history.start ();
  3. Myrouter.route ("Search/:query/:filter1-:filter2/page:page", "Search", function (query, Filter1, Filter2, page) {
  4. Console.log (query, Filter1, Filter2, page);
  5. });
  6. Change URL hash to #search/foo/today-newest/page1
  7. Window.location.hash = "Search/foo/today-newest/page1";

Tips:

    • If you enclose the URL parameter in ' () ', it becomes an optional argument. If there is no ' () ', then the URL will only run all parameters that are defined in the route string.

Common way to match a URL to route ()

The route () method optionally receives a regular expression value as the first argument and does not accept a string value. This will be a better way to help you adjust the matching URL. In the following code, I show how to match a particular character to a route.

 
  
  
  1. var myrouter = new Backbone.router ();
  2. Backbone.history.start ();
  3. Myrouter.route (/(HELPSUPPORTANSWERSQA)/, "Help", function () {
  4. Console.log ("The URL hash just change to/#help");
  5. });
  6. Change the URL hash to "#help"
  7. Window.location.hash = "Help";
  8. Change the URL hash to "#qa" settimeout (function () {window.location.hash = QA;},2000);
  9. Change the URL to "#support" settimeout (function () {Window.location.hash = "support";},4000);

Route broadcast a "Route:callback-name" embedded event

When a route matches a namespace, and the callback function calls a "route" embedded event, it means that the called callback function name has been broadcast by backbone. The On () or Listento () event method can be used to embed the "Route:nameofcallbackfunction" event.

In the following code, when the search callback function is called, I take advantage of the On () and Listento () listener and invoke the additional callback function.

 
  
  
  1. var myRouter = New Backbone.router ();
  2.  
  3. backbone.history.start ();
  4.  
  5. myrouter.route ("Search/:query", "Search", function (query) {
  6. Console.log (query+) 0 ");
  7.  
  8. //on ()
  9. myrouter.on ("Route:search", function (query) {
  10. Console.log (query+ "1");
  11. //listento ()
  12. backbone.listento (Myrouter, "Route:search", function (query) {
  13.  
  14. //to change the URL hash to #search/foo/today-newest/page1
  15. window.location.hash = "Search/foo";

Note that on () and Listento () can pass any URL parameters.

Tips:

    • When a route matches, there is also an "route" event assigned to the "Route:callback-name" event that is embedded in the routing object.

Using navigate () to navigate the path manually

I called the route in the previous code example by changing the Window.location.hash value of the backbone listening in the browser. Using the Navigate () method, we can achieve the same goal. In the following code, I call the Navigate () method to pass a route string to the navigation instead of updating the hash value in the browser.

 
  
  
  1. var myrouter = new Backbone.router ();
  2. Backbone.history.start ();
  3. Myrouter.route ("test/:p Aram", "Test", function (param) {
  4. Console.log (param);
  5. });
  6. Use navigate () to pass the URL and then run to get the log "foo"
  7. Myrouter.navigate ("Test/foo", {
  8. Trigger:true
  9. });

Tips:

    1. By default, navigate () updates the URL in the browser (processing history and Back buttons) without invoking the routing callback function. You must pass the Trigger:true option to navigate () in order to update the URL in the browser and invoke the callback function that the link attaches to the route.
    2. By default, navigate () assumes that you want to change the URL and update the browser history. If you do not want to update the browser history (press the Back button), you can pass the Replace:true option to navigate (). This will simply replace the current URL without updating the browser history.


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.

Tags Index: