Analysis of MVC/MVP/MVVM mode in front-end development

Source: Internet
Author: User

Both MVC,MVP and MVVM are common software architecture design patterns (architectural pattern), which improve the way code is organized by separating the points of Interest. Unlike design patterns, which are simply abstract methods to solve a class of problems, an architectural pattern often uses multiple design patterns.

To understand mvc, mvp, and mvvm, you need to know their similarities and differences. The different parts are C (Controller), P (Presenter), VM (view-model), and the same part is MV (model-view).

Model&view

Here is a component that can be used to add and subtract values: values are displayed above, two buttons can add and subtract values, and the value of the operation will be updated to Display.

We will follow this "chestnut" and try to use JavaScript to implement a simple Web application with MVC/MVP/MVVM Mode.

Model

The model layer is used to encapsulate the data related to the business logic of the application and how the data is Processed. Here we encapsulate the required numerical variables in model and define the three operation numerical methods of add, sub, and Getval.

varMyApp = {};//create this Application objectmyapp. Model=function() {    varval = 0;//data that needs to be manipulated    /*ways to manipulate data*/     this. Add =function(v) {if(val <) val + =v;    };  this. Sub =function(v) {if(val > 0) val-=v;    };  this. Getval =function() {        returnval; };};
View

View is a layer of views that is responsible for the presentation of the Data.

function () {    /**/    var $num = $ (' #num '),        = $ (' #increase ' ),        = $ (' #decrease ');     /*  *    /thisfunction(model)        {+ ' RMB ');};    } ;

The logic of data from the model layer to the view layer is now completed through MODEL&VIEW. But for an application that is far from enough, we also need to respond to the User's actions, update the view and model Synchronously. thus, in mvc, controller controllers are introduced to define how the user interface responds to user input, which connects models and views, controls the flow of applications, and handles changes in user behavior and Data.

Mvc

At that time, the world of computer chaos, seamless, and then appeared a creator, the real world Abstract model form, the Human-computer interaction from the application logic to form a view, and then have air, water, chicken, eggs and so On.
--"the Distortion of Front-End mvc"

In the 70 's, the American Xerox Parker Research center, The company that invented the graphical user interface (GUI), developed the Smalltalk programming language and began using it to write graphical interface applications.

By the time Smalltalk-80 this version, an engineer called Trygve Reenskaug designed the MVC (model-view-controller) architecture pattern for smalltalk, greatly reducing the difficulty of managing GUI Applications. It is then heavily used to build desktop and Server-side applications.

, solid lines represent method calls, and dashed lines represent event Notifications.

MVC allows you to change the way a view responds to a user's input without changing the view, and the user gives the view a handle to the controller, and the event that responds to the view in the controller calls the Model's interface to manipulate the Data. Notifies the relevant view to update once the model has Changed.

Model

The model layer is used to store the data of the business, and once the data has changed, the models will notify the relevant VIEW.

MyApp. Model =function() {    varval = 0;  this. Add =function(v) {if(val <) val + =v;    };  this. Sub =function(v) {if(val > 0) val-=v;    };  this. Getval =function() {        returnval;    }; /* Viewer Mode */varSelf = this, views= [];  this. Register =function(view) {views.push (view);    };  this. notify =function() {         for(vari = 0; I < views.length; i++) {views[i].render (self); }    };};

The observer pattern is used between model and view, and the view is registered on this model in advance to see the model to update the data that changed on the Model.

View

The policy mode is used between the view and controller, where view introduces an instance of the controller to implement a specific response strategy, such as the pest button click event:

function (controller) {    var $num = $ (' #num '),        = $ (' #increase '),        = $ (' # Decrease ');      this function (model) {        + ' RMB ');    };     /*   bind event   *    /$incBtn. Click (controller.increase);    $DECBTN. Click (controller.decrease);};

If you want to implement a policy that responds differently, simply replace it with a different controller instance.

Controller

The controller is the link between the model and the view, and MVC encapsulates the response mechanism in the controller object, and when the user interacts with your application, the event trigger in the director begins to Work.

MyApp. Controller =function() {    varModel =NULL, view=NULL;  this. init =function() {        /*Initialize model and view*/Model=Newmyapp.        Model (); View=NewMyApp. View ( this); /*view to model registration, when the model update will be to notify the view*/Model.register (view);    Model.notify ();    }; /*let model update values and notify view update views*/     this. Increase =function() {model.add (1);    Model.notify ();    };  this. Decrease =function() {model.sub (1);    Model.notify (); };};

Here we instantiate the view and register it with the corresponding model instance, and when the model changes, it notifies the view to do the update, and the Observer pattern is used Here.

When we execute the application, we use the controller to initialize It:

(function() {    varnew  myapp. Controller ();    Controller.init ();}) ();

It is obvious that the business logic of the MVC pattern is mainly focused on the controller, while the front-end view has the ability to handle user events independently, and this layer becomes bloated when each event flows through the Controller. and MVC in the view and controller is generally one by one corresponding, tied up to represent a component, the view and the controller is too close to the connection to make the controller reusability becomes a problem, if you want multiple views to share a controller what to do? Here's a solution:

To the glory of the King Yajing ~ actually I want to say is the MVP mode ...

Mvp

MVP (model-view-presenter) is an improvement of the MVC model, proposed by Ibm's subsidiary, Taligent. And MVC are the Same: Controller/presenter is responsible for business logic, Model Management data, View is responsible for the Display.

Although in mvc, view is directly accessible to model, the view in the MVP does not use the model directly, but instead provides an interface for presenter, allowing presenter to update the model, and then update the view through the Observer Mode.

In contrast to mvc, the MVP model separates views and models by decoupling the view and model, which makes the delineation of responsibilities clearer; since view does not rely on model, it can be pulled out of the view to make components, it only needs to provide a series of interfaces to the upper Operation.

Model
function () {    var val = 0;      this function (v) {        if (val <) val + = v;    };      this function (v) {        if (val > 0) val-= v;    }    ;  this function () {        return  val;    };} ;

The model layer is still the primary business-related data and the method for processing the Data.

View
 myapp. View = function   () { var  $num = $ (' #num '  = $ (' #increase '  this . render = function   + ' $ '  this . init = function   () { var  presenter = new myapp.        Presenter (this  

The MVP defines the interface between the presenter and the view, and the User's actions on the view are shifted to Presenter. For example, here the view exposure Setter interface Let presenter call, pending presenter notify Model update, presenter call View provides interface update VIEW.

Presenter
 myapp. Presenter = function   (view) { var  _model = new   myapp.    Model ();     var  _view = view;    _view.render (_model);  this . increase = function   () {_model.add ( 1 this . decrease = function   () {_model.sub ( 1

Presenter as the "middleman" between view and model, in addition to the basic business logic, there is a lot of code that needs to "manually synchronize" the data from view to model and from model to view, so that the presenter appears heavy and difficult to maintain. And because there is no data binding, if the demand for Presenter view rendering increases, it has to pay too much attention to a particular view, and presenter needs to change once the demand for the views Changes.

When running a program, view is the Entry:

(function() {    varnew  myapp. View ();    View.init ();}) ();
MVVM

MVVM (model-view-viewmodel) was first proposed by microsoft. ViewModel refers to "model of View"--a view of the Models. This concept was stir by the front end for some time, so many beginners compared jquery with Vue ...

MVVM automates the synchronization logic of view and Model. Previously presenter-responsible view and model synchronization is no longer manual, but to the framework to provide the data binding function to be responsible, just tell it the view display data corresponding to which part of the Model.

Here we use Vue to complete this Chestnut.

Model

In mvvm, we can refer to the model as the data layer because it only focuses on the data itself and does not care about any behavior (formatted data is the responsibility of the view), which can be understood as a json-like data object.

var data = {    0};
View

Unlike mvc/mvp, the view in MVVM uses template syntax to render data into the DOM declaratively, and when ViewModel updates the model, it is updated to view by data binding. The wording is as Follows:

<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>
ViewModel

ViewModel is basically the MVC controller and MVP of the presenter, but also the focus of the whole model, business logic is also mainly focused here, one of the core is data binding, will be discussed later. Unlike the mvp, there is no interface provided by view for presente, and the data synchronization between the view and model previously handled by presenter is given to the data binding in the viewmodel, and when the model is changed, ViewModel will automatically update, ViewModel changes, model will be Updated.

New Vue ({    ' #myapp ',    data:data,    methods: {        add (v) {            if(this). Val <) {                this. val + = v;            }        ,        Sub (v) {            if  (This. val > 0) {                this. val-= v;}}}    ); 

overall, a lot more streamlined than mvc/mvp, not only simplifies the business and interface dependencies, but also solves the problem of frequent data updates (previously tedious to use jquery to manipulate the dom). Because in mvvm, view does not know the existence of model, ViewModel and model are not aware of view, this low-coupling mode can make the development process easier and improve the reusability of the Application.

Data binding

Bidirectional data binding, which can be easily and inappropriately understood as a template engine, but rendered in real time based on data changes. --"under The interface: restore the real mv* model"

In vue, the bidirectional binding technique (two-way-data-binding) is used, which means that the change in the view can change the model in real time, and the model changes can be updated to view in real Time.

"this thing is supposed to be patented."

The techniques for implementing bidirectional data binding differ in different MVVM frameworks. At present, some mainstream front-end frameworks implement data binding in roughly the following ways:

    • Data Hijacking (Vue)
    • Publish-subscribe mode (Knockout, Backbone)
    • Dirty value Check (Angular)

We mainly talk about Vue Here.

Vue uses the data hijacking & Publish-subscribe mode to Object.defineProperty() hijack (monitor) the properties by ES5, getter setter and notifies subscribers when data (objects) change, triggering a corresponding listener callback. also, because synchronization is triggered on different data, it is possible to send changes to the bound view precisely, rather than performing a single test on all the Data. To implement two-way data binding in vue, you can roughly divide three modules: Observer, Compile, watcher,

    • Observer Data Listener
      Responsible for listening to all the properties of the data object (data Hijacking) and notifying subscribers when the data changes.

    • Compiler Instruction Parser
      Scans the template, parses the instruction, and then binds the specified Event.

    • Watcher Subscribers
      Associate Observer and compile, be able to subscribe and receive notification of property changes, execute the corresponding operation of the instruction binding, and update the VIEW. Update () is a method of its own that executes the callback that is bound in compile and updates the VIEW.

Data hijacking

The data is generally hijacked by the Object.defineproperty method, the corresponding function in Vue defineReactive , its ordinary object hijacking of the lite code is as Follows:

varFoo ={name:' Vue ', Version:' 2.0 '}functionobserve (data) {if(!data | |typeofdata!== ' object ') {        return    }    //using recursive hijacking object PropertiesObject.keys (data). ForEach (function(key) {definereactive (data, key, data[key]); })}functiondefinereactive (obj, key, Value) {//listen for sub-attributes such as ' name ' or ' version ' in the data object hereobserve (value) object.defineproperty (obj, key, {get:functionreactivegetter () {returnvalue}, set:functionreactivesetter (newval) {if(value = = =Newval) {                return            } Else{value=newval console.log (' listening success: ${value}-${newval} ')} }})}observe (foo) Foo.name= ' angular '//"listening success: Vue ---angular"

The above completes the listener to the data object, then also needs to notify the subscriber after the supervisor hears the change, this needs implements a message subscriber, Dep watcher by Dep adding the subscriber, when the data change is triggered Dep.notify() , watcher calls own update() method to complete the view Update.

It says that it's getting farther away from the subject ... Data hijacking is the first to talk about it ~ for the students who want to go deep vue.js can refer to three shares four Vue.js source learning notes

Summarize

The purpose of mv* is to decouple the three blocks of application data, business logic, and interface, and to isolate concerns, not only for team collaboration and testing, but also for the maintenance and management of the pot . The business logic is no longer concerned with the reading and writing of the underlying data, which is presented to the business logic layer in the form of Objects. From Mvc--and MVP--and MVVM--like a weird escalation process, they're all based on the evolution of the Times and the application environment on the basis of MVC.

It's better to get to know them first when we're struggling with what architectural patterns or frameworks we use. Think of business scenarios and development needs, and there will be the best solution for different needs. We use this framework to represent the ideas that identify with it, and believe it can improve development efficiency to solve current problems, not just because everyone is learning.

Some people are bored with new technologies and others are dismissive of new technologies. As Dickens wrote in a tale of the Cities:

This is the best of times, this is the worst of times, this is the age of wisdom, it is the age of folly, this is the time of faith, This is the time of doubt, this is the season of light, this is the season of darkness, This is the spring of hope, it is the winter of despair, people have everything in front of them, people are ; People are going straight to Hell.

Please keep a hug change heart, in the face of new technology is not blind, not Old-fashioned.

Some reference resources:
GUI architectures
Under the Interface: restore the true mv* mode
The front-end MVC distortion record
In-depth understanding of JavaScript series
250 rows to implement a simple MVVM

Analysis of MVC/MVP/MVVM mode in front-end development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.