javaScript——What is the difference between mvvm and mvc design patterns?

php是最好的语言
Release: 2018-07-24 16:36:28
Original
3143 people have browsed it

Let’s briefly talk about what MVVM and MVC design patterns are. In MVC, View can directly access Model! Therefore, the View will contain Model information and inevitably some business logic.

1. What is the difference between MVVM and MVC?

In MVC, View can directly access Model! Therefore, the View will contain Model information and inevitably some business logic. The MVC model focuses on the invariance of the Model. Therefore, in the MVC model, the Model does not depend on the View, but the View does depend on the Model. Not only that, because some business logic is implemented in View, it is also difficult to change View. At least those business logic cannot be reused. All communication in MVC is one-way. Conceptually, MVVM is a pattern that truly separates page and data logic and can achieve two-way binding of data.

2. What is VM?

VM is a data model abstracted from View. It should be noted that during development, VM is no longer writing other things that are not related to the data, such as some methods.

3. How do MVVM and code correspond?

MVVM is composed of three parts: Model, View, and VM. Model corresponds to the logical part that obtains data and processes the data into something that can be used by VM, while View corresponds to the data display and data binding part, and VM is an abstract data model object.

4. Which frameworks use the MVVM model?

There are many front-end frameworks that use the MVVM pattern, such as AngularJS, avalon, emberjs, knockoutjs, winjs, react, riverts, way, vue, regular, drop and other frameworks

5. MVC, MVP, MVVM usage scenarios?

To understand their usage scenarios, you should first understand their advantages and disadvantages.

Advantages and Disadvantages of MVC:

Advantages:

1. Separate all business logic into the Controller, with a high degree of modularity. When the business logic changes, there is no need to change the View and Model, just change the Controller to another Controller (Swappable Controller).

2. Observer mode can update multiple views at the same time.

Disadvantages:

1. Controller testing is difficult. Because the view synchronization operation is performed by the View itself, and the View can only run in an environment with a UI. When unit testing the Controller without a UI environment, the correctness of the Controller's business logic cannot be verified: when the Controller updates the Model, it cannot assert the update operation of the View.

2. View cannot be componentized. View is strongly dependent on a specific Model. If you need to extract this View as a reusable component for another application, it will be difficult. Because the Domain Model of different programs is different

Advantages and disadvantages of MVP:

Advantages:

1. Easy to test. Presenter communicates with View through interfaces, when unit testing Presenter does not depend on the UI environment. You can Mock a View object, which only needs to implement the View interface. Then dependencies are injected into Presenter, and the correctness of Presenter's business logic can be completely tested during unit testing.

2. View can be componentized. In MVP, View does not depend on Model. This allows View to be separated from specific business scenarios. It can be said that View can be completely ignorant of business logic. It only needs to provide a series of interfaces for upper-layer operations. In this way, you can make highly reusable View components.

Disadvantages:

1. In addition to business logic, Presenter also has a large amount of manual synchronization logic for View->Model and Model->View, making Presenter cumbersome and difficult to maintain. It will be more difficult.

Advantages and disadvantages of MVVM:

Advantages:

1. Improve maintainability. It solves the problem of a large number of manual View and Model synchronization in MVP and provides a two-way binding mechanism. Improved code maintainability.

2. Simplify testing. Because the synchronization logic is handled by Binder, the View changes simultaneously with the Model, so you only need to ensure the correctness of the Model, and the View will be correct. Greatly reduced testing of View synchronization updates.

Disadvantages:

1. The too simple graphical interface is not suitable, or it is overkill.

2. For large graphics applications, there are many view states, and the cost of building and maintaining ViewModel will be relatively high.

3. The data binding declaration is written imperatively in the View template, and these contents cannot be interrupted and debugged.

Как видно из вышеперечисленных преимуществ и недостатков, из MVC->MVP->MVVM это похоже на процесс убийства монстров и обновления. Последний решает проблемы, оставленные первым, оптимизирует недостатки первого в преимущества и выбирает наиболее подходящую структуру в соответствии с реальным проектом.

6. Как выбрать между Angular, avalon и Vue?

Angular содержит все части MV* и имеет собственный набор правил, поэтому подходит для ПК, но структура кода будет более понятной; avalon легкий и подходит для старых браузеров. Vue имеет высокая степень поддержки браузера, минимальная поддержка - IE6, поэтому он подходит для проектов, совместимых с браузером Lao Liu; Vue в основном легкий и используется только в качестве части представления в MV*. Его преимущества заключаются в легкости, прост в освоении и использовании, но недостатком является то, что это большой проект. При его использовании его приходится использовать с другими фреймворками или библиотеками, что довольно хлопотно.

7.Зарождение развития.

MVVM(Model-View-ViewModel)框架的由来便是MVP(Model-View-Presenter)模式与WPF结合的应用方式时发展演变过来的一种新型架构框架。它立足于原有MVP框架并且把WPF的新特性糅合进去,以应对客户日益复杂的需求变化。
Copy after login

8. Как реализовать двустороннюю привязку данных.

В настоящее время существует три основных способа реализации двусторонней привязки данных:

1. Ручная привязка

Более старый метод реализации использует режим программирования наблюдателя, Основная идея состоит в том, чтобы определить методы получения и установки для объекта данных, вручную вызвать получение или установку данных при вызове и запустить операцию рендеринга уровня пользовательского интерфейса после изменения данных; в основном применяется сцена, в которой представление управляет изменением данных. для ввода, выбора и текстовой области. Когда уровень пользовательского интерфейса изменяется, он запускает события для изменения данных в слое данных, прослушивая изменение dom, нажатие клавиши, нажатие клавиши и другие события. Весь процесс завершается вызовами функций.

2. Механизм обнаружения грязных данных

Представленный типичной платформой mvvm angularjs, angular обновляет уровень пользовательского интерфейса, проверяя грязные данные. Что касается обнаружения загрязнений в Angular, вам нужно знать несколько вещей:

  • Механизм обнаружения загрязнений не использует обнаружение по расписанию.

  • Время обнаружения загрязнений — это момент изменения данных.

  • angular инкапсулирует часто используемые события DOM, события xhr и т. д. и запускает процесс дайджеста для входа в angular.

  • В процессе дайджеста он будет проходить от корневой области и проверять всех наблюдателей. (Что касается конкретного дизайна angular, вы можете посмотреть другие документы, здесь мы обсуждаем только привязку данных), затем давайте посмотрим, как выполнить грязное обнаружение: в основном через набор данных найти все элементы, связанные с данными, а затем сравнить данные изменяются, и если они изменяются, выполняется командная операция.

3. Взлом данных на внешнем интерфейсе

Основная идея состоит в том, чтобы использовать Object.defineProperty для мониторинга получения и установки свойств объекта данных. чтение и Во время операции присваивания вызывается инструкция узла, поэтому просто используйте наиболее распространенный знак = для присвоения значения.

9. Преобразование MVC-MVVM.

Ядром программного обеспечения являются данные.Бизнес-логика возникает вокруг генерации, модификации и других изменений данных. Для отображения данных возникли различные интерфейсные технологии. Без хорошо спроектированного кода часто будет возникать связь между уровнем данных (уровнем сохраняемости), уровнем бизнес-логики и кодом интерфейса.

Поскольку mvc не обеспечивает полного разделения представления и модели, в отличие от mvvm, это приводит к переходу от mvc к mvvm.

10. Какие шаблоны проектирования использует MVVM?

Шаблон наблюдателя.

Рекомендации по теме:

Видео:Видеоурок по JavaScript

Видео:Видеоурок по начальной разработке мини-программы WeChat

The above is the detailed content of javaScript——What is the difference between mvvm and mvc design patterns?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!