MVVM framework

What is MVVM? MVVM is short for Model-View-ViewModel.

MVVM was first proposed by Microsoft. It draws on the MVC idea of ​​desktop applications. In the front-end page, the Model is represented by a pure JavaScript object, and the View is responsible for display. The two have achieved the maximum separation.

The ViewModel is what associates the Model and the View. The ViewModel is responsible for synchronizing the Model's data to the View for display, and is also responsible for synchronizing the View's modifications back to the Model.

What is the difference between an MVVM framework and jQuery for manipulating the DOM?

Let's first look at an example of modifying two DOM nodes implemented with jQuery:

<!-- HTML -->
<p>Hello, <span id="name">Bart</span>!</p> <p>You are <span id="age">12</span>.</p> 

Hello, Bart!

You are 12.

Modify the contents of the name and age nodes with jQuery:

var name = 'Homer';
var age = 51;

$('#name').text(name);
$('#age').text(age);

If we use the MVVM framework to achieve the same function, we don't care about the structure of the DOM in the first place, but how the data is stored. The easiest way to store data is to use JavaScript objects:

var person = {
    name: 'Bart',
    age: 12
};

We think of variables personas Models, some DOM nodes in HTML as Views, and assume that they are related.

To change the displayed name from Bartto Homerand the displayed age from 12to 51, we do not manipulate the DOM, but directly modify the JavaScript object:

person.name = 'Homer';
person.age = 51;

Executing the above code, we were surprised to find that changing the state of a JavaScript object would cause a corresponding change in the DOM structure! This shifts our focus from how to manipulate the DOM to how to update the state of JavaScript objects, which are much easier to manipulate than the DOM!

This is the design idea of ​​MVVM: pay attention to the changes of the Model, and let the MVVM framework automatically update the state of the DOM, thus freeing the developer from the tedious steps of operating the DOM!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324844125&siteId=291194637