This section code address

What is encapsulation

It can be interpreted as “put something complicated into a box” and can be used with a simple command

For example,

  • Computer notebook is CPU, memory, hard disk, motherboard, display card packaging
  • The user only needs to touch the monitor, keyboard, mouse, trackpad and other devices
  • Can operate complex computers

interface

  • Something encapsulated needs to expose some functionality to the outside world

  • These functions are interfaces, such as USB interface and HDMI interface

    • Interfaces need to be well documented
    • Manufacturers around the world can follow the USB interface documentation to produce HARDWARE with USB interface
    • Shenzhen Huaqiang North is based on a variety of documents, quickly copy the production of apple data line… (The function is similar and the price is cheaper)
    • This is the beauty of interfaces, which any vendor can do as long as they know the functionality and implementation details
  • As long as the device supports these interfaces, it can communicate with the encapsulated object

    • For example, when we type on a keyboard, the computer can pick up which key we hit
  • For example, the keyboard and mouse support USB ports

  • Display supports HDMI interface

    • All display manufacturers around the world can connect their products to any computer because there is a unified standard for interface

    • The old ones are: VGA port (large and slow)

    • The latest: Lightning interface, HDMI interface (there are new standards)

(Schematic diagram)


This section of the implementation of the “My library” inside the DOM encapsulation of a variety of bizarre operations

  • Document. getElementById is too long, so it’s wrapped and called get or find

  • Create an element by encapsulating it as a create element, without writing document.createElement… Such a complicated word

  • The functions that encapsulate get, find, and create are interfaces

  • These interfaces can be invoked on all pages

The term

library

  • We call the tool code that we make available to other people, libraries.
    • It’s a collection of useful functions in one place, called a library.
  • For example, jQuery and Underscore are libraries that provide many functions for users to call

API

  • The functions or properties (functions) exposed by the library are called apis (Application programming interfaces)
  • API: Application Programming Interface

The framework

  • When your library gets big and you have to learn to understand it
  • So this library is called a framework, like Vue/React

Pay attention to

  • Most of the programming language is very informal and has no fixed interpretation

    • Maybe a programmer has written something that covers a lot of content, and the author himself is not sure how to define it, so he casually calls it a “library.”
    • If someone disagrees, take time to discuss and define
  • So just be spontaneous

    • We call the “small features” libraries and the “big features” frameworks

Packaging technology

Let’s start with encapsulation

Encapsulate DOM manipulation in two different styles

  1. Object Style (namespace style)
  2. Chain Style (jQuery style)

DOM library initialization ⭕️

Create dom-1 project directory > SRC directory > index.html, main.js, dom.js

index.html

<body>The sample<! -- Note that dom.js is introduced first; Dom is not defined -->
  <script src="dom.js"></script>
  <script src="main.js"></script>
</body>
Copy the code

dom.js

Dom libraries (objects) and encapsulated functions (create) have two forms of rendering relationships

1

window.dom = {}
dom.create = function () {}   // window.dom.create omits the prefix window
Copy the code

2

window.dom = {
  create: function () {}}// 👆 can be further simplified: omit function // ES6
window.dom = {
  create(){}}Copy the code

Example: Encapsulating create code

For more code, see the address directly

Create Creates a node.

Write 1

  • Call with the name of the label to create
window.dom = {}
dom.create = function (tagName) {
  return document.createElement(tagName)
}
Copy the code

Write 2

First edition buggy
  • Call directly into the label structure
  • But td/tr/tbody… The label in this table, it’s going to return undefined.
  • These tags can’t be placed directly inside divs; they usually need to be wrapped around a table tag
dom.create = function (html) {
  // const container = document.createElement('div')  
  const container = document.createElement('template')
  // If the container is a div, it cannot hold TD... Etc.
  // Use 
       as a container that can hold any element.
  container.innerHTML = html
  return container.children[0]}Copy the code
The correct code
dom.create = function (html) {
  const container = document.createElement("template")
  container.innerHTML = html.trim()
  // trim Trim both ends of the string
  // Because we use firstChild to fetch elements, if the HTML is passed in with a space in front of it, only the space (text element) is retrieved, not the tag element.
  // Trim () must be done in advance
  return container.content.firstChild
}
Copy the code

main.js

Call to method 1

const div = dom.create("div")
console.log(div)   
      
Copy the code

Call to method 2

const div = dom.create("<div><span>123</span></div>")
console.log(div)   123
Copy the code

Object style

Also called namespace style

  • Window.dom is the global object we provide

Window.dom is a very large code.

This section code address

increase

After () : It’s just out in 2020

InsertBefore syntax: parent. InsertBefore (the child node to be inserted, before which child node to insert)

Dom. Create ('<div>hi</div>')   // Used to create a node
dom.after(node,node2)          // Add a brother
dom.before(node,node2)         // Use it to add an older brother
dom.append(parent,child)       // For a new son
dom.wrap(`<div></div>`)        // For new fathers
Copy the code

code

window.dom = { 
  create(string){ // Create a node
    const container = document.createElement("template")
    container.innerHTML = string.trim()
    return container.content.firstChild
  },
  after(node, node2){ // Add sibling nodes
    node.parentNode.insertBefore(node2, node.nextSibling)
  }, 
  before(node, node2){ // Add sibling nodes
    node.parentNode.insertBefore(node2, node)
  },
  append(parent, node){ // Add a child node
    parent.appendChild(node)
  }, 
  wrap(node, parent){ // Add a parent nodeDom.before (node, parent) dom.append(parent, node)}};Copy the code

delete

Dom.remove (node) is used to remove the node dom.empty(parent) is used to remove descendantsCopy the code

code

window.dom = {
  remove(node){
    node.parentNode.removeChild(node)
    return node
  },
  empty(node){
    let array = []
    let x = node.firstChild   
    // This is the most common way of thinking about data structures. It is similar to recursion in a loop (keep looking for the next one until they are all deleted).
    while (x) {
      array.push(dom.remove(x))
      x = node.firstChild 
    }
    return array
  }
}
Copy the code

change

Used overload and adaptation.

  • Overloading: Pass different numbers of arguments, execute different code
  • Adaptation: make a lot of decisions (JS data types), when to execute this sentence, when to execute that sentence
dom.attr(node, 'title',?)// Used to read and write attributes
dom.text(node, ?)                 // Used to read and write text content
dom.html(node, ?)                 // Used to read and write HTML content
dom.style(node, {color: 'red'})   // Used for modification
dom.class.add(node, 'blue')       // Used to add
dom.class.remove(node, 'blue')    // Used for deletion
dom.on(node, 'click', fn)         // Used to add event listeners
dom.off(node, 'click', fn)        // Used to delete event listeners
Copy the code

code

dom.attr = function (node, name, value) {
  if (arguments.length === 3) {
    node.setAttribute(name, value)
  } else if (arguments.length === 2) {
    return node.getAttribute(name)
  }
}

dom.text = function (node, string) { 
  if (arguments.length === 2) { 
    if ("innerText" in node) {
      node.innerText = string
    } else {
      node.textContent = string
    }
  } else if (arguments.length === 1) {
    if ("innerText" in node) {
      return node.innerText
    } else {
      return node.textContent
    }
  }
}

dom.html = function (node, string) {
  if (arguments.length === 2) {
    node.innerHTML = string
  } else if (arguments.length === 1) { 
    return node.innerHTML
  }
}

dom.style = function (node, name, value) {  // 3 call forms
  if (arguments.length === 3) {
    node.style[name] = value
  } else if (arguments.length === 2) {
    if (typeof name === "string") {
      return node.style[name]
    } else if (name instanceof Object) { 
      const object = name
      for (let key in object) {
        node.style[key] = object[key]
      }
    }
  }
}

dom.class = {
  add(node, className) {
    node.classList.add(className)
  },
  remove(node, className) {
    node.classList.remove(className)
  },
  has(node, className) {
    return node.classList.contains(className)
  }
}

dom.on = function (node, eventName, fn) {
  node.addEventListener(eventName, fn)
}

dom.off = function (node, eventName, fn) {
  node.removeEventListener(eventName, fn)
}
Copy the code

check

dom.find('selector')    // Used to get tags or tags
dom.parent(node)     // Used to get the parent element
dom.children(node)   // Used to get child elements
dom.siblings(node)   // Used to get sibling elements
dom.next(node)       // To get the younger brother
dom.previous(node)   // Get the older brother
dom.each(nodes, fn)  // Used to traverse all nodes
dom.index(node)      // Used to get the ranking number
Copy the code

code

dom.find = function (selector, scope) {
  return (scope || document).querySelectorAll(selector) 
}

dom.parent = function (node) {
  return node.parentNode
}

dom.children = function (node) {
  return node.children
}

dom.siblings = function (node) {
  return Array.from(node.parentNode.children).filter(n= >n ! == node) } dom.next =function (node) {
  let x = node.nextSibling
  while (x && x.nodeType === 3) { 
    x = x.nextSibling
  }
  return x
}

dom.previous = function (node) {
  let x = node.previousSibling
  while (x && x.nodeType === 3) {
    x = x.previousSibling
  }
  return x
}

dom.each = function (nodeList, fn) {
  for (let i = 0; i < nodeList.length; i++) {
    fn.call(null, nodeList[i])
  }
}

dom.index = function (node) {
  const list = node.parentNode.children
  let i
  for (i = 0; i < list.length; i++) {
    if (list[i] === node) {
      break}}return i
}
Copy the code

Conclusion 1

  • The above code, except “create node, use template”, other methods are basically using DOM native API to implement
  • It doesn’t matter how deep the library is, you end up with if-else, for, while loops
    • No matter what language, you only need three expressions to implement logic: sequential execution, if/else, and loop

Conclusion 2

  • The best way to learn, is to see the author’s ideas, according to his ideas to achieve. Vue authors, for example, write all their ideas down in a VUE document, just read it.

This is classic code that many programmers have been working on for years. You just have to stand on the shoulders of giants and keep going up