MVVM
The MVVM introduction
Core ideas:
Divide and conquer (different business code in different business modules, organized together by specific logic)
MVVM is actually M, V, VM, which is short for model-view-viewModel. It is an architectural pattern based on front-end development, and its core is to provide two-way data binding between View and ViewModel, which makes the state change of ViewModel can be automatically passed to the View, namely the so-called two-way data binding.
Vue.js is a Javascript library that provides mVVM-style bi-directional data binding, focusing on the View layer. At its heart is the VM in MVVM, which is the ViewModel. The ViewModel is responsible for connecting the View and Model, ensuring consistency between View and data. This lightweight architecture makes front-end development more efficient and convenient.
What is Model, View, ViewModel?
Model
The Model can be called the data layer because it only cares about the data itself and does not care about any behavior (formatting the data is the responsibility of the View), so it can be thought of as a JSON-like data object that mainly stores the data in the page.
// It can be thought of as a jSON-like data object
var data = {
val: 0
};
Copy the code
The Model layer represents models, data, and the business logic for data modification and manipulation can be defined in the Model layer.
View
Unlike MVC/MVP, the View in MVVM uses template syntax to declaratively render data into the DOM. When the ViewModel updates the Model, it updates it to the View via data binding.
Such as:
div id="myapp">
<div>
<span>{{ val }}rmb</span>
</div>
<div>
<button v-on:click="sub(1)">-</button>
<button v-on:click="add(1)">+</button>
</div>
</div>
Copy the code
The View layer represents views, templates, and is responsible for translating the data model into a UI presentation.
ViewModel
The core of the MVVM pattern is the bridge between the View and the Model. It has two directions:
- Turn the Model into a View, which translates the data passed from the back end into the page you see. This is done by data binding.
- Turn the View into a Model, and turn the page you see into data on the back end. This is done by DOM event listening.
Both directions are implemented, which we call bi-directional data binding.
Such as:
new vue({
el: '#myapp'.data: data,
methods: {
add(v) {
if(this.val < 100) {
this.val += v; }},sub(v) {
if(this.val > 0) {
this.val -= v; }}}});Copy the code
The MVVM model
In the MVVM architecture, the View layer and the Model layer are not directly connected, but interact through the ViewModel layer.
The ViewModel is usually implemented as an observer. When the data changes, the ViewModel can listen for changes in the data and notify the corresponding view of automatic updates. When the user manipulates the view, the ViewModel can also listen for changes in the view and notify the data of changes. This effectively implements two-way data binding.
The ViewModel layer connects the View layer to the Model layer through two-way data binding, making the synchronization between the View layer and the Model layer completely automatic. Therefore, developers only need to focus on the business logic and do not need to manually manipulate the DOM, leaving the complex maintenance of data state to the MVVM for unified management.
Vue. Js is the embodiment of MVVM
The implementation of vue. js “hijacks” the data (Model). When the data changes, the data will start to hijack the binding method to update the view.
MVVM in VUE:
Case analysis:
As you can see from the example, the ViewModel connects the View layer to the Model layer through two-way data binding, and the synchronization between the View and Model is completely automatic without human intervention.
Some implementation details of vue.js on bidirectional data binding
Now I have a brief look at vue.js implementation details of two-way data binding. A deep dive into the MVVM model takes you through the bidirectional binding of vue.js
Vue implements data binding using getters and setters for Object.defineProperty in conjunction with the observer pattern. When passing an ordinary javascript Object to a Vue instance as its data option, Vue iterates through its properties, turning them into getters/setters with Object.defineProperty. Getters/setters are invisible to the user, but internally they let Vue track dependencies. Notify properties of changes when they are accessed and modified.
Vue bidirectional binding icon:
- Obiect.defineproperty (obiect.defineProperty); obiect.defineProperty (obiect.defineProperty); obiect.defineProperty (obiect.defineProperty)
- The Complie directive parser, which scans and parses the directives of each element node, replaces data according to the directive template, and binds the Observer to Complie, subscribes to receive notification of each attribute change, and executes the corresponding callback function of the directive binding
- The Watcher subscriber, acting as a bridge between Observer and Complie, can subscribe to and receive notification of each property change, executing the corresponding callback function of the directive binding.
- The Dep message subscriber maintains an array internally to collect subscribers (Watcher). Data changes trigger the notify function, which calls the update method of the subscriber.
The above process can be summarized as:
The Observer is equivalent to the Model layer observing the data in the VUE instance and notifying Watcher subscribers when the data changes.
The Compile directive parser, located in the View layer, initializes the View, binds the data changes to the update function, and passes it to Watcher subscribers.
Watcher is the core of the entire model, corresponding to the ViewModel layer, linking Observer and Compile. All Watchers are stored in the Dep subscriber. Watcher processes the data changes monitored by the Observer according to the corresponding callback function and feeds the data back to the View layer to update the interface View.
MVC
Introduction of the MVC
The MVC pattern represents the Model-View-Controller pattern. This pattern is used for layered development of applications.
MVC Model, View, Controller
Model = Model
The Model is the part of the application that handles the application’s data logic. Typically, model objects are responsible for accessing data in a database.
Model defines the data Model for this module. Embodied in the code as the data manager, Model is responsible for data acquisition and storage.
Model is not only the data manager, but also responsible for data acquisition by it. Data cannot be generated without foundation. It is either the data obtained from the server, or the data in the local database, or the form that the user fills in on the UI is about to be uploaded to the server for storage, so the data source is needed. Since the Model is the data manager, it is naturally responsible for retrieving the data.
MVC allows you to change the way the View responds to the user input without changing the View. The user’s operation on the View is handed over to the Controller. In the Controller, the interface of the Model is called to operate on the data in response to the events of the View.
Here, we encapsulate the numerical variables needed in Model, and define add, sub, and getVal to manipulate the numerical methods
var myapp = {}; // Create the application object
myapp.Model = function() {
var val = 0;
this.add = function(v) {
if (val < 100) val += v;
};
this.sub = function(v) {
if (val > 0) val -= v;
};
this.getVal = function() {
returnval; }; / * Observer mode * /var self = this,
views = [];
this.register = function(view) {
views.push(view);
};
this.notify = function() {
for(var i = 0; i < views.length; i++) { views[i].render(self); }}; };Copy the code
The observer pattern is used between the Model and the View, where the View registers with the Model in advance to observe the Model in order to update the data that changes on the Model.
View
A View is the part of the application that handles the display of data. Views are usually created from model data.
A View, a View, is simply what we see on the interface.
The policy pattern is used between view and Controller, where the View introduces instances of controller to implement specific response policies, such as the button click event in this chestnut:
myapp.View = function(controller) {
var $num = $('#num'),
$incBtn = $('#increase'),
$decBtn = $('#decrease');
this.render = function(model) {
$num.text(model.getVal() + 'rmb');
};
/* Bind event */
$incBtn.click(controller.increase);
$decBtn.click(controller.decrease);
};
Copy the code
If you want to implement a different response policy you can simply replace it with a different Controller instance.
Controller (Controller)
A Controller is the part of the application that handles user interaction. Typically the controller is responsible for reading data from the view, controlling user input, and sending data to the model.
The Controller is the data and View coordinator in MVC. That is, the Controller assigns data from the Model to the View to display (or the View receives input from the user and the Controller passes the data to the Model to save locally or upload to the server).
myapp.Controller = function() {
var model = null,
view = null;
this.init = function() {
/* Initialize Model and View */
model = new myapp.Model();
view = new myapp.View(this);
/* View registers with Model and notifies View when Model updates */
model.register(view);
model.notify();
};
/* Let the Model update the value and tell the View to update the View */
this.increase = function() {
model.add(1);
model.notify();
};
this.decrease = function() {
model.sub(1);
model.notify();
};
};
Copy the code
Here we instantiate the View and register it with the corresponding Model instance. When the Model changes, we notify the View to update it. Here we use the observer mode.
When we execute the application, we initialize it with Controller:
(function() {
var controller = newmyapp.Controller(); controller.init(); }) ();Copy the code
Communication in MVC
The communication between the parts is as follows, all communication is one-way.
- The View sends instructions to the Controller
- After the Controller completes the business logic, it asks the Model to change state
- The Model sends the new data to the View, and the user gets feedback
When accepting user directives, MVC can be broken down into two ways:
One is to receive instructions from the View and pass them to the Controller:
The other is to receive instructions directly through the controller:
The business logic of MVC mode mainly focuses on Controller, while the front View actually has the ability to independently process user events. When each event flows through Controller, this layer will become very bloated. In addition, View and Controller are generally one-to-one in MVC, which represent a component together. The too close connection between View and Controller makes the reusability of Controller a problem.
The article source
Vue learning -MVVM model
MVC and MVVM models