What is MVC?

MVC(Model View Controller) is an architectural design pattern.

M: Model, or data layer (data model), is responsible for manipulating all data.

V: View, namely the view layer, is responsible for all UI interfaces, is provided to the user’s operation interface, is the shell of the program.

C: Controller, namely the control layer, is responsible for selecting “data in the data layer” according to user input instructions from the “view layer” and performing corresponding operations (binding events, etc.) to produce the final result.

The three layers are closely linked but independent of each other, and changes within each layer do not affect the other layers. Each layer provides an Interface that can be invoked by the upper layer. In this way, the software can be modular, changing the look and feel or changing the data without changing other layers, greatly facilitating maintenance and upgrades.

In fact, there is no clear definition of MVC. I understand MVC as an abstract concept that structures code.

1. Data layer (data Model)

// Example let Model = {data: {data source}, create: {add data}, what is MVC? Delete: {delete data}, update(data) {object.assign (m.data, data); Eventbus. trigger("m:update"); //eventBus triggers the 'm:update' message to inform the View to refresh the interface}, get: {get data},};Copy the code

2. View layer

// Example let View={el: element to refresh, HTML: 'refresh content to display on page' init(){v.l: initialize element to refresh}, render(){refresh page}}Copy the code

3. The Controller control layer

Let Controller={init(){v.init()// Initialize View v.ender ()// Render the page for the first time c.autobindevents ()// Automatic event binding Eventbus. on('m:update',()=>{v.render()}// When enentsBus triggers 'm:update', events:{events are stored in a hash table}, // for example: events: { 'click #add1': 'add', 'click #minus1': 'minus', 'click #mul2': 'mul', 'click #divide2': 'div', }, add() { m.update({n: m.data.n + 1}) }, minus() { m.update({n: m.data.n - 1}) }, mul() { m.update({n: m.data.n * 2}) }, div() { m.update({n: M.data.n / 2})}, method(){data= new data m.data.n / 2}, AutoBindEvents (){for (let key in c.vents){// Iterate through the events table, Const Value = c[c.vents [key]] const spaceIndex = key.indexof (" ") const part1 = key.slice(0, SpaceIndex) // Get 'click' const part2 = key.slice(spaceIndex + 1) // get '#add1' v.eln (part1, part2, value)}}Copy the code

Second, the EventBus

1. What is EventBus?

As mentioned earlier, the THREE LAYERS of MVC are closely linked but independent of each other, and changes within each layer do not affect the other layers. When layer to layer communication is needed, EventBus is needed. EventBus is mainly used for listening and communication between components.

2. The EventBus commonly used API

Eventbus.on () Listens to events

Eventbus.trigger () Triggers an event

Eventbus.on () Cancels listening events

Eventbus.trigger ('m:updated') eventBus.on(' M :updated',()=>{// Monitor event v.ender (m.data.n)})Copy the code

Table driver programming

Table-Driven Methods (Table-Driven Methods) is a programming mode.

Application scenario: Eliminate frequent if else or switch case logical structure code, make code more simple

  • In fact, any information can be selected by the table. In simple cases, it is easier to use logical statements, but once the number of judgment conditions increases, it may be necessary to write a lot of repeated judgment statements. At this time, we realize the conditional judgment by traversing the table, which will get twice the result with half the effort.

Case 1

Requirement: Write a function that passes in the date and returns the corresponding day

  • Leap year meet :(four years a embellish and one hundred years not embellish) or (four hundred years embellish)

Regular writing

function getDay(year, month) { let isLeapYear = year % 4 === 0 && year % 100 ! == 0 || year % 400 === 0 ? 1: 0 if (month === 2) { return 28 + isLeapYear } else if (month===1||month===3||month===5||month===7||month===8||month===10||month===12) { return 31 } else if (month === 4 || month === 6 || month === 9 || month === 11) { return 30 } } console.log(getDay(2020, Log (getDay(2020, 2)) // 29 console.log(getDay(2019, 2)) // 28 Copy the codeCopy the code

Table driven writing

Const monthDays = [[31,28,31,30,31,30,31,31,30,31,30,31], [31,29,31,30,31,30,31,31,30,31,30,31]] function getDay (year, month) {let isLeapYear = year % 4 = = = 0 && year % 100! == 0 || year % 400 === 0 ? 1: 0 return monthDays[isLeapYear][month-1] } console.log(getDay(2020, 12)) // 31 console.log(getDay(2020, 2)) // 29 console.log(getDay(2019, 2)) // 28 Copy codeCopy the code

Case 2

Listen for element binding events

Regular writing

add1(){ ... } min1(){ ... } mul2(){ ... } div2(){ ... } document.querySelector('#add1').addEventListener('click', add1) document.querySelector('#min1').addEventListener('click', min1) document.querySelector('#mul2').addEventListener('click', mul2) document.querySelector('#div2').addEventListener('click', div2) document........ Copy the codeCopy the code

Table driven writing

Const controller = {add1(){}, min1(){}, mul2(){}, div2(){}, events: Click #min1: "min1", "click #mul2": "mul2", "click #div2": "div2" }, AutoBindEvents () {for(let key in this.events){const handler = this[this.events[key]] const handler = this[this.events[key]] const [the event, the selector] = key. The split (" ") / / / "click", "# min1" $(" container "). On the event, the selector, handler) / / the extracted values to monitor events})}}Copy the code

The “regular” code is simpler and straightforward, but it’s too repetitive. As the size of the data increases, so does the amount of code to write if there are 10 or 100 listening events

Table driven programming allows code to have a steady level of complexity, keeping it simple regardless of data size.

  • Avoid repetition and keep it simple. That’s what programmers are looking for

Four, about modularity

MDN documentation: JavaScript modules

1. The modular

The modular value here is front-end modularity, which is an important prerequisite for MVC. Modularization is the extraction of relatively independent code from a large piece of code into small modules that are relatively independent from each other for future maintenance.

The syntax of ES6 introduces Import and export to achieve modularity.

export default c; Export {c}; // Another way to export. Remember to copy the code with curly bracesCopy the code

2. Minimum knowledge principle

Use a module with minimal knowledge, normally we need to introduce CSS and JS in HTML, now only need to introduce a module JS is enough.

3.M+V+C

Each module can be usedM+V+CThe pattern is done, even if MVC is invueIs reduced to a V.

4. (Abstract Thinking)

Keep repetitive things simple and abstract

  • Repetitive code ==> abstracts into functions
  • The same attribute ==> is abstracted into a stereotype or class
  • The same stereotype ==> uses inheritance