HT for Web HTML5-tree component delay loading technology implementation

Source: Internet
Author: User
Tags emit

HT for Web the HTML5 tree component has a lazy load feature, which is useful for those who need to read hierarchical dependency data from the server, and then initiate requests to the server when the data needs to be fetched, which reduces server pressure and reduces browser latency. Let the page load more smoothly and enhance the user experience.

To get to the point, today's demo demo is that the client requests the server to read the system file directory structure and display the system file directory structure through the HT for Web HTML5 tree component .

First, we design the server, this time the demo server using node. js, with node. js Express,Socket.io, FS and HTTP four modules, the relevant knowledge of node. js, I do not elaborate here, a bunch of online teaching materials, here is recommended Socket.io the relevant entry http://socket.io/get-started/chat/ .

Service-Side Code code:

var fs = require (' FS '),    Express = require (' Express '),    app = Express (),    server = require (' http '). Createserver (APP),    io = require (' Socket.io ') (server),    root = '/users/admin/projects/ht-for-web/guide '; Io.on (' Connection ', function (socket) {    socket.on (' Explore ', function (URL) {        socket.emit (' file ', Walk (URL | | (root));});    App.use (express.static ('/users/admin/projects/ht-for-web ')); Server.listen (the function () {    Console.log (' Server is listening at Port 5000 ');});

IO listens to the connection event and obtains a socket;socket to listen to a custom event called explore, and after fetching the data through the URL parameters, a custom event called file is dispatched for the client to listen and handle accordingly. ; Set the project path with App.use combined with express.static, and finally let the server listen on port 5000.

Here, a simple server is set up and can now access the server through http://localhost:5000. Wait, there seems to be something missing. By the way, the method of obtaining the structure of the System file directory has been forgotten, OK, then we will first see how to get the whole station file code is written:

function Walk (PA) {    var dirlist = Fs.readdirsync (PA),        key = Pa.substring (Pa.lastindexof ('/') + 1),        obj = {
   name:key,            Path:pa,            Children: [],            files: []        };    Dirlist.foreach (function (item) {        var stats = fs.statsync (PA + '/' + item);        if (Stats.isdirectory ()) {            Obj.children.push (Walk (PA + '/' + item));        }        else {            Obj.files.push ({name:item, Dir:pa + '/' + item});        }    });    return obj;}

As you can see, the recursive way to traverse the sub-directory, the code is not very advanced place, I believe we can understand. Let's take a look at the effect of the operation:


duang~ file directory structure come out, is not feeling cool, this code amount is not small bar. In fact, the code is not much, paste it out people look:

<! DOCTYPE html>

This is all the HTML code, plus a blank line total of 50 lines, how, there is no sense that HT for the Web is very powerful. Don't say much, just to see what the code has done:

    • To use the Socket.io need to introduce <script src= "/socket.io/socket.io.js" ></script> in the page, in fact, in my project does not exist/socket.io /socket.io.js file, but it can be used normally, specifically what reason, I will not say, we study to go to it;
    • The most important thing is to introduce the HT for Web core package <script src= "/lib/core/ht.js" ></SCRIPT> If this package is not introduced, the following HT for Web Components cannot be used;
    • Next is the code, first create a data container datamodel, used to hold the node data of the file directory, and then create a TreeView object and reference just created to the data container, then through the socket to listen to the file event, the server to obtain the data returned, In the callback function, by calling the Createchildren and Createfiles functions, the File directory node object is created, added to the data container, and finally the data request is initiated to the server, that is, the Explore event is distributed through the socket.

The whole idea is this, of course, this is not the implementation of the tree component of the delay loading technology is still some gap, then theHT for Web HTML5 Tree component of the lazy loading technology is how to implement it? Don't worry, start exploring right away.

First we need to transform the way to get the file directory walk, because the method described above, using the loading of the whole station file directory, so we want to transform the walk method to only get a first-level directory structure, the transformation is very simple, is to transform the recursive part to get the current node can be, the specific code is as follows:

Obj.children.push (Walk (PA + '/' + item));//Change the above code to the code below Obj.children.push ({name:item, Path:pa + '/' + item});

This way, the server requests only the first level of the file directory structure under the current request path. The next step is to adjust the client code, first to set the tree to loader:

Tree.setloader ({    load:function (data) {        socket.emit (' Explore ', data.a (' path '));        DATA.A (' Loaded ', true);    },    isloaded:function (data) {        return data.a (' Loaded ');}    });

Loader contains two methods, load and isloaded, the functions of the two methods are loading data and determining whether the data has been loaded, in the Load method, the socket is dispatched explore event, the current node path is a parameter, to the server request data, The current node's loaded property is then set to true, and in the IsLoaded method, the loaded property of the current node is returned, and if true, tree will not request data to the server when the load method is executed.

Next, you need to remove the two callback methods for Createchildren, and set the loaded property of the created node to true in the Createfiles method so that there are no expanded icons before the nodes that are not directories. Createchildren and Createfiles Two methods the modified code is as follows:

function Createchildren (children, parent, DM) {    Children.foreach (function (child) {        var n = createdata (Child, parent);        Dm.add (n);    });} function Createfiles (files, parent, DM) {    Files.foreach (function (file) {        var n = createdata (file, parent);        N.A (' Loaded ', true);        Dm.add (n);    });}

So, theHT for Web HTML5-Tree component delay-loading technique is finished, and I print out the request path in the console of the server to see if this lazy load is true, such as:



See, the console Prints 4 records, the first one is the request to print with the directory, I expanded in the browser three directories, the console print its corresponding directory path.

And so on, now this directory looks good annoying, only the text, in addition to the seat of the expansion of the icon can be used to distinguish between files and directories, no other difference, so I decided to change it, so that each level of the directory has an icon, and different files corresponding to different icons, to see the effect of it:


How, is not a glance can see what file, this is the style above the problem, I will no longer one by one elaborated, directly on the code:

<! DOCTYPE html>

At the end, attach the full server code:

var fs = require (' FS '), Express = require (' Express '), App = Express (), Server = require (' http '). Createserver (APP) , IO = require (' Socket.io ') (server), root = '/users/admin/projects/ht-for-web/guide '; Io.on (' Connection ', function (so    Cket) {socket.on (' Explore ', function (URL) {socket.emit (' file ', Walk (url | | root)); });}); App.use (express.static ('/users/admin/projects/ht-for-web ')); Server.listen (the function () {Console.log (' server is listening at Port 5000 ');}); function Walk (PA) {var dirlist = Fs.readdirsync (PA), key = Pa.substring (Pa.lastindexof ('/') + 1), obj =    {Name:key, PATH:PA, Children: [], Files: []};        Dirlist.foreach (function (item) {var stats = Fs.statsync (PA + '/' + item);        if (Stats.isdirectory ()) {Obj.children.push ({name:item, Path:pa + '/' + item});        } else {Obj.files.push ({name:item, Dir:pa + '/' + item}); }    }); return obj;}


HT for Web HTML5-tree component delay loading technology implementation

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.