Summary of M(model) and MVC in MVC


Summary of M(model) and MVC in MVC

MVC encapsulates message.js (focus on understanding the encapsulation of M)

The source code of this blog is my online resume I am writing, and the blog is written after the previous one
Complete code (the project is not yet completed)
preview address

Used when previewing the project locallyhttp-server
make the code structured

V and C

Encapsulate the code of message.js into MVC mode,
Separate V and C first to make the code look organized
Modified structure:
Summary of M(model) and MVC in MVC

Complete code message.js

M (model) module for manipulating data

Model is a module for manipulating data, so LeanCloud is encapsulated as an object for manipulating data. The method of initializing and manipulating data is encapsulated in model:
Summary of M(model) and MVC in MVC
fetch()andsave()Return promise so that subsequent controller calls

The rest of the structure is modified as follows:
Summary of M(model) and MVC in MVC

  1. Pass the view and model to the controller and operate on it
  2. Add and initialize the model in the controller
  3. Use the functions that manipulate data in the model (fetch and save), and use .then() on the returned promise to continue writing success and failure codes

controllercallingfetch()andsave()And after receiving the returned Promise, you can write directlyasynchronous code, you can write what to do after success and failure.

Manipulate the data to the model, and then pass it to the controller for success or failure processing. The returned Promise will be followed by then. As for whether it succeeds or fails, it depends on the return information of the model layer

message.js separate M complete code in MVC

Summary of MVC

MVC is to divide the code into three parts

  1. V(view) is only responsible for what is visible.
  2. M (model) is only responsible for data-related operations, there will be no DOM, and no html/css operations. For example, there will only be methods for initializing the database and obtaining data in the modelfetch(), the way to save datasave()
  3. C (controller) is only responsible for combining these views and models, finding the view, finding the model, using the model to complete the data modification business, and modifying the display of the view

V: view
M: data
C: Controller

MVC is a form of code organization, not any kind of framework, nor any kind of technology. It is just the idea of ​​organizing code. What to do is to pass V and M to C, and C to coordinate

As for whether M, V, and C are objects or classes, it doesn’t matter. In js, MVC has three objects to take on three responsibilities

Logical order of MVC (green words)
Summary of M(model) and MVC in MVC
The model is dedicated to accessing the server (database on the server)