Director.js: A concise Chinese course for routing---clients

Source: Internet
Author: User

1. Intro

Recently learning to use director.js, it is quite easy to learn and easy to use. However, when the study began, after searching, but did not find the relevant Chinese course. So decided to bite E, the translation of the spare is also when it is to teach themselves and deepen understanding of it.

Director.js's official address can be found here, this tutorial is mainly from here.

2. What is Director.js?

Director.js as I understand it is the client's routing registration/parser, which, without refreshing the page, organizes different URL paths with the "#" symbol and matches different callback methods based on different URL paths. Popular Point says is what kind of path to do what kind of thing.

Director.js is suitable for client browsers and node. JS server-side applications, where there are only a small number of different ways to invoke methods in both scenarios. It is ideal for developing single-page programs and node. JS apps that don't need to be refreshed. In particular, the single-page program, for those who do not want to intervene in mobile app development, you can use this implementation of similar apps.

Director.js does not depend on any other JS libraries, such as jquery. But it is also very well integrated with jquery to use.

In this article, we mainly study its application on the client, node. JS server side is not discussed at this stage.

3, the simple start

As mentioned earlier: Director.js is organized by the "#" symbol, for example:

Http://www.demo.com/#/show
Http://www.demo.com/#/show/list
Http://www.demo.com/#/show/single

  

The route registration in the URL is reflected in the "#" symbol to identify the beginning of the route, and then use the "/" delimiter (the delimiter can be customized, described later) to define the route fragment. Client-side routing is essentially a URL that distinguishes between different states of an application and defines what should be done in different states. When a user accesses a different URL, director.js parses the routing information and tells the application what it needs to do.

The routing format can be referenced in detail:

The following is a simple example:

     '/books/view/:bookid ': Viewbook      };      var router = router (routes);      Router.init ();    </script>  

  

Used with jquery:

The following is a detailed description of the Director.js client-related APIs.

4. Initialization and routing Registration

The main object of Director.js is the router object, which is constructed as follows:

var router = new Router (routes);

  

The routes parameter passed in the constructor method is a routing table object that is an object with a key-value pair structure that allows multiple layers of nested definitions.

The key of the key-value pair corresponds to the path passed in the URL, typically a key corresponding to a portion of the cut by the delimiter, while the value of the key value pairs the name of the callback function that should be triggered by the path, pass in one or more function names, and use the array object when passing in multiple function names. In general, the callback function must be declared before the routing Table object is used, otherwise JS will error.

In addition, the callback function is generally not recommended for anonymous functions unless it is a special case, so be sure to declare and use it as soon as possible.

  var routes = {    '/dog ': Bark,        '/cat ': [Meow, Scratch]  };

In the example above, the corresponding URLs were: #/dog and #/cat

  

After declaring the router object, you need to call the Init () method for initialization, as follows:

var routes = {    '/dog ': Bark,        '/cat ': [Meow, Scratch]};var router = router (routes); Router.init ();

5, the immediate registration of the route

When we are developing some large-scale applications, it is generally not necessary to start with the required path and its corresponding callback functions are prepared beforehand. Most of the time, when we are doing a certain function, or if we are developing a module with a relatively low degree of independence, we know what path and callback function we need. This time we need to register the routing function in real time.

Director.js provides support for the instant registration feature through the "On" method, as shown in the following example:

var router = router (routes). Init (), ... router.on ('/rabbit ', function () {...})

6. Routed Events

A routed event is a fixed-named property in the routing registry that is defined when the route method Router.dispatch () is called, and the callback method that needs to be triggered when the route match succeeds (allowing multiple callback methods to be defined). The "on" method in the Instant registration function above is an event. Specific information is as follows:

    • On : The method to be executed when the route match is successful
    • Before: the method to execute before triggering the "on" method

Methods that are valid only on the client:

    • After : the method to be executed when leaving the current registration path
    • once: method that the current registration path executes only once
var routes = {      "/about/:id": {            before:function (ID) {alert ("Direct to:/home/about/" + ID);},            on:function (ID) {window.location = "/home/about/" + ID;}};

* Anonymous functions are used in the example above, only because they are convenient for example and are not recommended for use in this way

7. Configuration parameters

Director.js improves the flexibility of router objects by configuring some optional parameters. The settings for these parameters need to be router. The Configure () method is implemented.

var router = new director. Router (routes). Configure (options);

The specific configuration parameters are:

    • recurse: parameters that control the recursive triggering of the route, the optional value is "forward", "backward" and "false", the client's default value is "false", and the default value of the server is "backward"
    • Strict: When the value is "false", the path is allowed to end with a "/" (or another custom delimiter); The default is "true", indicating that the path is not allowed to end with "/"
    • Async: Synchronous asynchronous controller with a value of "Ture", "false", and a default value of "false"
    • delimiter: route delimiter, default value is "/"
    • NotFound: When the routing method Router.dispatch () is called, there is no method that fires when matching to any route
    • On : When the routing method Router.dispatch () is called, the method to be executed after any one of the routes has been successfully matched, and the difference from the "on" event in the routed event above is similar to the global and local concept, in the routing table only for the currently registered route , while "on" in the Configure method is for all routes in the global
    • before: when the routing method Router.dispatch () is called, the method that needs to be executed when any one of the routes match successfully and before "on", and the difference from the "before" event in the routed event above

Parameters that are valid only on the client:

    • resource: A string-based object used to bind the callback function. Use this parameter to implement the delay binding of the callback function (the original word is "late-binding", followed by the relevant detailed instructions)
    • After : The method that is triggered when the given path is no longer the currently active path, which can be understood as the method triggered after leaving the current path; the difference from the "after" event in the routed event above

* The above configuration parameters are explained in detail in the following

* Other parameters that are only valid on the client are html5history and Run_handler_in_init, which are related to HTML5 and are not discussed for the time being.

8. URL Matching

In the example of the routed event section, there is a route expression "/about/:id", where ":" The part defined later indicates that the part that corresponds to the actual path is the parameter that passed in the callback function, such as "#/about/5", where 5 is the value of the ID parameter. Parameter matching can also be defined in a nested way:

var router = router ({  '/about ': {    '/:id ': {      on:function (id) {Console.log (ID)}}}  );

In practical applications, our routes can become very complex, and simple expressions like "/about/:id" do not meet our needs. While Director.js supports the use of regular expressions to match complex route names, the matching values are passed as parameters to the callback function, for example:

var router = router ({  '/hello ': {     '/(\\w+) ': {      on:function (WHO) {Console.log (WHO)}}}  );

When the URL is passed into ' #/hello/world ', the callback function's Who=world

Support for more complex multi-parameter delivery:

var router = router ({  '/hello ': {    '/world/? [^\/]*] \ ([^\/]*)/? ': Function (A, b) {      console.log (A, b);}}  );

When the URL is passed into ' #/hello/world/johny/appleseed ', the callback function's A=johny,b=applesee

9. Recursive matching of routes

The recurse parameter in the global configuration determines how the path is hit in the routing table and the hit order. The hit modes include recursive hits and exact hits, and the hit order includes the positive sequence, the reverse order, and the interrupt.

When the parameter is set to "forward, backward", it indicates that the route is hit by a recursive hit, and is hit in the specified order, forward is the positive sequence, and backward is reversed. Routing if multiple route fragments are defined, their corresponding callback functions can be hit, meaning that a path can hit multiple functions.

When the value of this parameter is not specifically specified (that is, the default value "false"), it is indicated that the route is hit with an exact hit and needs to exactly match the entire path before it can be hit, meaning that a path can only hit one function.

When the URL is passed into "#/dog/angry", the routing table is registered as follows:

  var routes = {    '/dog ': {      '/angry ': {        on:growl      },      On:bark    }  };

  

Only the Growl method is hit when there is no way to specify a recursive match.

When the value of the specified recursive match parameter is backward, the Growl method is hit first, then the Bark method is hit, followed by the order of the path registration. As follows:

var router = router (routes). Configure ({recurse: ' backward '});

When the value of the specified recursive match parameter is forward, first hit the bark method and then hit the Growl method, followed by the sequence of the path registration. As follows:

var router = router (routes). Configure ({recurse: ' Forward '});

When a recursive match parameter is specified, "return false" is used in the hit function. is returned, the recursive hit is interrupted and returned directly. As follows:

  var routes = {    '/dog ': {      '/angry ': {        on:function () {return false;}      },      On:bark    }  };  var router = router (routes). Configure ({recurse: ' backward '});

Without interruption, the method under angry is hit first, and then the Bark method is hit, but after the return false statement is executed, the angry hit method is no longer recursive to hit another method (bark).

10. Resource parameters

The resource parameter in the global configuration is available only in the client app, which is a text object whose Text property values are primarily used to define the callback method name after the route match hit. It provides better encapsulation of the program for better structural design.

  var router = router ({'    /hello ': {      '/usa ': ' Americas ',      '/china ': ' Asia '    }  }). Configure ({resource: Container}). init ();  var container = {    americas:function () {return true;},    china:function () {return true;}  };

In the example, after the container object is defined in the routing object, I think this is the "delayed binding" feature that was previously said. Because the callback function bindings for a route must conform to the method used before the declaration, this example is clearly declared after use. But I tested it, this will be an error, or can not change the first declaration after the use of the order. So I haven't really figured out the meaning of late binding.

11. Summary

Director.js in the client application of the brief Chinese tutorial is these, with this knowledge to do a simple crud demo program is completely no problem. However, in the course of doing this demo, I feel that I have not realized the essence of director.js use. Because I called the Ajax method after the hit, my problem is that since the Ajax method has been used, why use Director.js? I still have to look at the "Bootstrap + requirejs+ director+ knockout + web API = A fashionable single-page program" This article and its examples to realize the essence of director.js. Also thank the author of this article for sharing.

There will be time to study and complement the server application tutorials, as well as several configuration parameters and methods under the HTML5 application. Students who need to know more details can go to its official address to chew E.

Director.js: A concise Chinese course for routing---clients

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.