Tutorial on developing tab instances using object-oriented method in native JS

Time:2022-5-4

This tutorial encapsulates an example of a tab through the object-oriented method of JS, and explains how the object-oriented function of JS is realized in the example.

Generally, the encapsulated tab program only needs a div element. Other elements are generated through JSON data, so the encapsulated tab instance is very convenient to call. First create a div element as follows:

 

This tutorial only explains the past and present life of object-oriented, and directly illustrates the specific practice through examples. First prepare the required JSON data, and then you can directly generate tabs in the instance. The data codes are as follows:

var oData = [
  {
    label:'html',
    Content: 'html is called hypertext markup language, which is an iconic language. It includes a series of tags. Through these tags, the document format on the network can be unified, and the scattered Internet resources can be connected into a logical whole. HTML text is descriptive text composed of HTML commands. HTML commands can describe text, graphics, animation, sound, tables, links, etc. "
  },
  {
    label:'css',
    Content: 'cascading style sheets (English full name: cascading style sheets) is a computer language used to represent file styles such as HTML (an application of Standard General Markup Language) or XML (a subset of Standard General Markup Language). CSS can not only modify the web page statically, but also format the elements of the web page dynamically with various scripting languages. "
  },
  {
    label:'javascript',
    Content: 'JavaScript (JS for short) is a lightweight, interpretive or just in time compiled programming language with function priority. Although it is famous as a scripting language for developing web pages, it is also used in many non browser environments. JavaScript is based on prototype programming, multi paradigm dynamic scripting language, and supports object-oriented, imperative and declarative (such as functional programming). "
  },
];

 

Now you can analyze functions according to conventions and write specific code according to steps.

1. Create constructor
Native JavaScript instance objects are generally created through constructors. Therefore, before generating an instance object of a tab, first create a constructor, as shown below:

//Create a tab constructor, elem: DOM element; Data: generate tab data; Option: tab object related option properties
function TabClass(elem,data){

}

 

2. Set attributes, create labels and content elements in the constructor, as shown below:

function TabClass(elem,data,option){
  //Set data
  this.data = data;
  //Settings tab wrap
  this.wrap = elem;
  //Create label package
  this.labelBox = document.createElement('ul');
  //Set label package class
  this.labelBox.className = 'label_box';
  //Create content package
  this.contentBox = document.createElement('div');
  //Set content wrap class
  this.contentBox.className = 'content_box';
}

 

3. Set the default option properties in the constructor, such as the event of switching labels, which labels are displayed by default, etc. As follows:

function TabClass(elem,data,option=null){

  /*...*/

  //Set default properties
  this.options = {
    //The default switching tab is click event
    event:'click',
    //By default, the current label displays the first one
    index:0
  }
  //Modify option properties
  if(option instanceof Object){
    for(let k in option){
      this.options[k] = option[k];
    }
  }
}

 

4. Create the createdataelement method on the prototype of the constructor.
In the createdataelement method, the tag and content elements are generated from JSON data, and all elements are put into the package element. As follows:

TabClass.prototype.creatDataElem = function(){
  //Declare tag HTML code string variable
  var sLabel = '';
  //Declaration content HTML code string variable
  var sContent = '';
  //Generate labels and content elements by looping data
  this.data.forEach((e,i)=>{
    //Default current label and display content in judgment options
    if(i==this.options.index){  
      sLabel += '' + e.label + '';
      sContent += '' + e.content + '';
    }else{
      //The label is generated through the label attribute in the data. The data index attribute is the index of the current label, which is used to switch labels
      sLabel += '' + e.label + '';
      //Generate content through the content attribute in the data
      sContent += '' + e.content + '';
    }
  });
  //Put the label and content into the package element respectively
  this.labelBox.innerHTML = sLabel;
  this.contentBox.innerHTML = sContent;
  //Put labels and content into outsourcing elements
  this.wrap.appendChild(this.labelBox);
  this.wrap.appendChild(this.contentBox);
}

 

5. Create an init method on the prototype of the constructor to initialize the tab instance object.
In the init method, call the createdataelement method to generate DOM elements; Bind events to label wrapping elements, which are used to switch labels, etc. As follows:

TabClass.prototype.init = function(){
  //Statement_ The self variable is used to point to the instance object in the event function
  var _self = this;
  //Call the createdataelement method to generate DOM elements
  this.creatDataElem();
  //Bind events on tags
  this.labelBox.addEventListener(this.options.event,function(event){
    //Get the clicked DOM element
    var eTarget = event.target;
    //Judge whether the currently clicked tag is not the current tag
    if(eTarget.nodeName.toLowerCase() == 'li' && eTarget.className != 'active'){
      //Modify current label
      _self.options.index = eTarget.dataset.index;
      //Regenerate DOM elements
      _self.creatDataElem();
    }
  });
}

 

6. call this in the tabclass constructor Init is initialized as follows:

function TabClass(elem,data,option){
  
  /* ...  */
  
  /* ...  */
  
  //Initialize instance object
  this.init();
}

 

Now you can get the outsourcing element and generate the tab instance. The code is as follows:

var eContainer = document.getElementById('tabContainer');
new TabClass(eContainer,oData);

 

You can write styles according to your preferences to realize tab layout. The specific effects are as follows:

 

 

After being encapsulated into an object, it is very convenient to use. If you want to display the second tag by default and bind the mouseover event, you can add options as follows:

var eContainer = document.getElementById('tabContainer');
new TabClass(eContainer,oData,{index:1,event:'mouseover'});