preface

A good JS code follows the following principles

  • Each is responsible for its own responsibilities: that is, HTML is responsible for the structure of the page, CSS is responsible for element styles, and JS is responsible for interaction and behavior.

  • Component encapsulation: Component refers to a Web page extracted from a template (HTML), style (CSS) and function (JS) unit, a good component should have encapsulation, correctness, scalability, reuse.

  • Process abstraction: Writing and using functions as black boxes is also called process abstraction.

The company accountable

example

By writing a section of JS, control a web page, let it support light and dark browsing mode. What would you do if you did it?

Late night canteen: version one

const btn = document.getElementById('modeBtn'); btn.addEventListener('click', (e) => { const body = document.body; If (e. arget. InnerHTML = = = '🌞') {body. Style. BackgroundColor = 'black'; body.style.color = 'white'; E. arget. InnerHTML = '🌜'; } else { body.style.backgroundColor = 'white'; body.style.color = 'black'; E. arget. InnerHTML = '🌞'; }});Copy the code

Late night canteen: version 2

const btn = document.getElementById('modeBtn');
btn.addEventListener('click', (e) => {
  const body = document.body;
  if(body.className !== 'night') {
    body.className = 'night';
  } else {
    body.className = '';
  }
});
Copy the code
body, html { width: 100%; height: 100%; max-width: 600px; padding: 0; margin: 0; overflow: hidden; } body { padding: 10px; box-sizing: border-box; transition: all 1s; } div.pic img { width: 100%; } #modeBtn { font-size: 2rem; float: right; border: none; outline: none; cursor: pointer; background: inherit; } body.night { background-color: black; color: white; transition: all 1s; } #modeBtn::after {content: '🌞'; } body. Night #modeBtn::after {content: '🌜'; }Copy the code

Late night canteen: version 3

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content="ie=edge"> <title> </title> <body> <input id="modeCheckBox" type="checkbox"> <div class="content"> <header> <label id="modeBtn" for="modeCheckBox"></label> < h1 > dining room in the middle of the night < / h1 > < header > < main > < div class = "PIC" > < img SRC = "https://p2.ssl.qhimg.com/t0120cc20854dc91c1e.jpg" > < / div > <div class="description"> <p> This is a special canteen that is open from midnight to 7 am. The boss here is not very talkative, but always makes people eat tears in their eyes. Here, the self-abasement dancer encounters a veteran dancer who has retired from the dance industry for many years. The veteran inspires young people by telling about his embarrassing experience, and finally makes them regain confidence. The bestie broke up because they ate their favorite food and recalled their former friendship. Optimistic terminally ill patient encounters the girl with the same destiny, two people love each other and give strength to each other, accompany each other to walk perfectly the last journey; Blind pursuit of career success of white-collar workers, here to make real warm heart friends, found that the truth is more meaningful than success. Food, stories and true feelings are the themes of the whole play, which teaches people to face gains and losses calmly and to be full of expectations and enthusiasm for life. Behind each story is full of deep feeling, plot ups and downs, unforgettable [6]. </p> </div> </main> </div> </body> </html>Copy the code
body, html { width: 100%; height: 100%; max-width: 600px; padding: 0; margin: 0; overflow: hidden; } body { box-sizing: border-box; } .content { padding: 10px; transition: background-color 1s, color 1s; } div.pic img { width: 100%; } #modeCheckBox { display: none; } #modeCheckBox:checked + .content { background-color: black; color: white; transition: all 1s; } #modeBtn { font-size: 2rem; float: right; } #modeBtn::after {content: '🌞'; } #modeCheckBox:checked +. Content #modeBtn::after {content: '🌜'; }Copy the code

Late night canteen: Conclusion

  • HTML/CSS/JS is responsible

  • Unnecessary direct manipulation of styles by JS should be avoided

  • You can use class to represent state

  • Pure presentation class interaction seeks zero JS scheme

Component packaging

Components are units of Web pages that contain templates (HTML), functions (JS), and styles (CSS). Good components have encapsulation, correctness, extensibility, and reuse.

example

Write an e-commerce website with native JSShuffling figureHow should it be done?

Structure design: HTML

Structure: the HTML

As a typical list structure, we can use unordered lists<ul>Element to implement.

Display effect: CSS

Performance: CSS

  • Use CSS absolute positioning to overlap images in the same place

  • Use the modifier for the state of the rotation diagram switch

  • Use CSS Transition to animate the rotation diagram

Behavior design: API

Behavior: JS

  • API design should ensure atomic operation, single responsibility and flexibility.
class Slider{
  constructor(id){
    this.container = document.getElementById(id);
    this.items = this.container
    .querySelectorAll('.slider-list__item, .slider-list__item--selected');
  }
  getSelectedItem(){
    const selected = this.container
      .querySelector('.slider-list__item--selected');
    return selected
  }
  getSelectedItemIndex(){
    return Array.from(this.items).indexOf(this.getSelectedItem());
  }
  slideTo(idx){
    const selected = this.getSelectedItem();
    if(selected){ 
      selected.className = 'slider-list__item';
    }
    const item = this.items[idx];
    if(item){
      item.className = 'slider-list__item--selected';
    }
  }
  slideNext(){
    const currentIdx = this.getSelectedItemIndex();
    const nextIdx = (currentIdx + 1) % this.items.length;
    this.slideTo(nextIdx);
  }
  slidePrevious(){
    const currentIdx = this.getSelectedItemIndex();
    const previousIdx = (this.items.length + currentIdx - 1)
      % this.items.length;
    this.slideTo(previousIdx);  
  }
}

const slider = new Slider('my-slider');
slider.slideTo(1);
Copy the code

Behavior design: Control flow

Behavior: Control flow

  • Use custom events to decouple.

Summary: Basic method

  • The structure design

  • Show the effect

  • Behavior design

    • API (function)

    • Event(Control flow)

Refactoring: plug-in

The decoupling

  • Extract control elements into plug-ins

  • Plug-ins and components are linked by dependency injection

Refactoring: templated

The decoupling

  • Template HTML to make it easier to extend

Refactoring: Component framework

abstract

  • Abstract out common component models

conclusion

  • Component design principles: encapsulation, correctness, extensibility, reuse

  • Steps to implement components: structural design, presentation, behavior design

  • Three times in the reconstruction

    • pluggable

    • templated

    • Abstraction (Component framework)

  • If there is any mistake above, please point out in the comment section, thank you!

After reading it, give it a thumbs-up and then walk away