search
HomeWeb Front-endJS TutorialIntroduction to JavaScript framework (xmlplus) components (Nine) Tree (Tree)

xmlplus is a JavaScript framework for rapid development of front-end and back-end projects. This article mainly introduces the tree of the xmlplus component design series, which has certain reference value. Interested friends can refer to it

The tree component is a component with a hierarchical structure and is widely used in various kind of scene. This chapter will implement a simple tree component. Although its functionality is limited, you can extend it to implement the tree component you need.

Data source

The data source of the tree component can be a data object in JSON format, or it can be a XML structured data or other hierarchical structured data. This chapter will use data objects with the following JSON format.

var data = {
 name: 'My Tree',
 children: [
 { name: 'hello' },
 { name: 'world' },
 {
  name: 'child folder',
  children: [
  { name: 'alice' }
  ]
 }
 ]
};

In the above data source, the name value will be displayed as the name of the tree node, and the array containing children represents the children of the node.

Design of recursive structure

The object is composed of the list elements ul and li in HTML. It has a natural tree structure. We might as well use them as Basic elements for building tree components. The outermost layer of the tree component must be a ul element, so we can temporarily define the tree component as follows:

Tree: {
 xml: `<ul id=&#39;tree&#39;>
   <Item id=&#39;item&#39;/>
   </ul>`
}

The undefined component Item here is a sub-item component that needs to be defined recursively. It will be based on The provided data recursively generates descendant objects. The following is a possible design:

Item: {
 xml: `<li id=&#39;item&#39;>
   <p id=&#39;content&#39;>
    <span id=&#39;neme&#39;/><span id=&#39;expand&#39;/>
   </p>
   <ul id=&#39;entries&#39;/>
   </li>`,
 map: { defer: "entries" }
}

Note that the above neme object is used to display the name attribute. The expand object is used to expand or close child object entries. Child object entries are set up to require lazy instantiation, and will only be instantiated when the user clicks on the expand object to expand the child.

Loading and rendering of data

As mentioned in the previous section, we set the child object entries to be instantiated lazily. Therefore, the data setting interface provided for the sub-item Item should not instantiate the entries immediately. Below we first give the data interface function.

Item: {
 // css, xml, map 项同上
 fun: function (sys, items, opts) {
  var data;
  function val(value) {
   data = value;
   sys.neme.text(data.name);
   data.children && data.children.length && sys.expand.show().text(" [+]");
  }
  return { val: val };
 }
}

This interface function val only sets the content related to the current node. Next we listen to the click event of the expand object and complete the instantiation of the component object entries in a timely manner.

Item: {
 // css, xml, map 项同上
 fun: function (sys, items, opts) {
  var data, open;
  sys.expand.on("click", function () {
   open = !open;
   sys.expand.text(open ? " [-]" : " [+]");
   open ? (sys.entries.show() && load()) : sys.entries.hide();
  });
  function load() {
   if ( sys.entries.children().length == 0 )
    for ( var item of data.children )
    sys.add.before("Item").value().val(item);
  }
  function val(value) {
   data = value;
   sys.neme.text(data.name);
   data.children && data.children.length && sys.expand.show().text(" [+]");
  }
  return { val: val };
 }
}

The above code contains an open parameter, which records whether the current node is in an expanded state for use by related listeners.

Dynamicly adding nodes

Now we make a small extension to the above component so that it supports the function of dynamically adding tree nodes. First, we add a trigger button to the child of the entries object and name it add.

Item: {
 xml: "<li id=&#39;item&#39;>
   <p id=&#39;content&#39;>
    <span id=&#39;neme&#39;/><span id=&#39;expand&#39;/>
   </p>
   <ul id=&#39;entries&#39;>
    <li id=&#39;add&#39;>+</li>
   </ul>
   </li>",
 map: { defer: "entries" }
}

Secondly, you need to listen to the click event of the add object and complete the addition of the object in the listener.

Item: {
 // css, xml, map 项同前
 fun: function (sys, items, opts) {
  var data, open;
  sys.item.on("click", "//*[@id=&#39;add&#39;]", function () {
   var stuff = {name: &#39;new stuff&#39;};
   data.children.push(stuff);
   sys.add.before("Item").value().val(stuff);
  });
  // 其余代码同前
 }
}

It should be noted here that the listening method for the add object cannot be used directly: sys.add.on("click",...), but the proxy method should be used, otherwise an error will be reported. . Because its parent is a lazy-instantiated component, the add object is not visible until the entries object is instantiated.

Complete tree component

Based on the above content, a complete version of the tree component is now given:

Tree: {
 css: `#tree { font-family: Menlo, Consolas, monospace; color: #444; }
   #tree, #tree ul { padding-left: 1em; line-height: 1.5em; list-style-type: dot; }`,
 xml: `<ul id=&#39;tree&#39;>
   <Item id=&#39;item&#39;/>
   </ul>`,
 fun: function (sys, items, opts) {
  return items.item;
 }
},
Item: {
 css: "#item { cursor: pointer; }",
 xml: `<li id=&#39;item&#39;>
   <p id=&#39;content&#39;>
    <span id=&#39;neme&#39;/><span id=&#39;expand&#39;/>
   </p>
   <ul id=&#39;entries&#39;>
    <li id=&#39;add&#39;>+</li>
   </ul>
   </li>`,
 map: { defer: "entries" },
 fun: function (sys, items, opts) {
  var data, open;
  sys.item.on("click", "//*[@id=&#39;add&#39;]", function () {
   var stuff = {name: &#39;new stuff&#39;};
   data.children.push(stuff);
   sys.add.before("Item").value().val(stuff);
  });
  sys.expand.on("click", function () {
   open = !open;
   sys.expand.text(open ? " [-]" : " [+]");
   open ? (sys.entries.show() && load()) : sys.entries.hide();
  });
  function load() {
   if ( sys.entries.children().length == 1 )
    for ( var item of data.children )
    sys.add.before("Item").value().val(item);
  }
  function val(value) {
   data = value;
   sys.neme.text(data.name);
   data.children && data.children.length && sys.expand.show().text(" [+]");
  }
  return { val: val };
 }
}

In The tree component in actual applications will have more functions than here. You can further improve it based on the above code, such as adding some ICON icons, making sub-items draggable, etc. However, it is very necessary to avoid complicating the code as much as possible during the improvement process. It is necessary to appropriately strip off some code and encapsulate it into components.

This series of articles is based on the xmlplus framework. If you don’t know much about xmlplus, you can visit www.xmlplus.cn. Detailed getting started documentation is available here.

【Related recommendations】

1. Free js online video tutorial

2. JavaScript Chinese Reference Manual

3. php.cn Dugu Jiujian (3) - JavaScript video tutorial

The above is the detailed content of Introduction to JavaScript framework (xmlplus) components (Nine) Tree (Tree). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft