Explore the transformation from MVC to MVVM + Flux architecture Patterns

Source: Internet
Author: User

This article starts with my blog

In business, the general MVVM framework is typically used in conjunction with the Data State Library (redux, MOBX, etc.), and this article uses a small demo to tell why the data State Library is attractive.

From MVC to the MVVM pattern.

Traditional MVC architecture (such as JSP) in today's mobile traffic in the age of gold, a more troublesome problem is that there will be a lot of global repeated rendering. But the MVC architecture is a good thing, it has a clear division of data, views, logic, so the front-end MVC framework (such as Backbone.js) out, for many small business scenarios, the front-end MVC framework is sufficient, it can also be used to separate front-end development of single page application, So where is its flaw?

Take Backbone.js said that its model exposes the set method, which means that the data of the same model can be modified in more than one view, and then the data of a model corresponds to the rendering of multiple view, as shown in. When there is too much business logic, multiple Model and multiple View will be coupled to a piece, you can think of a bug to be more painful when troubleshooting.

The MVVM framework solves the above two points perfectly for traditional MVC architecture with low performance (multiple global rendering) and a sore point for the high coupling of the front-end MVC framework (Model and View). You can see the two-way binding of the previously written MVVM framework parsing

Only MVVM

Suppose there is a scenario where you query the criteria in the input box, click the query, and then return the content in the list. As shown in the following:

Assuming the implementation of react, the idea is to call the query interface, after the successful invocation of the data will be obtained by setState depositing into the list, the listing shows some of the code as follows:

ConstDecorate=(listcomponent)= class extendsComponent{  Constructor(){    Super() This. State = { List:[]}  }  Componentdidmount(){    Fetch('./list.json ')      . Then(RES)= Res.JSON())      . Then(Result=  This.setState({ List: result.Data }))}  Render(){    return(<Listcomponent data={ This. State.List} />    )  }}

Next to the encapsulated decorate component, the list component that is passed into the stateless function is used to present the listing data, with the following code:

function   List  (props) { return  (<  Div>  { props .  Data . map  (R =>  <  p key={ r
     . id  }>{ r . content  }<  /P>    )  Span class= "ss" >}   </div  > ) }  /code> 

You can see that the List component is equivalent to the View layer, while the encapsulated decorate component is the Model layer. But in doing so, the business logic is written into the components. And we expect to get a pure Model layer and View layer. Then let's see how the Flux architecture pattern solves this problem.

Inductive Flux Architecture mode

The 4 important components of the flux architecture pattern and their relationship as shown below will gradually uncover the flux architecture pattern in the order of Dispatch,store, action, and view.

From the source code of Flux can be seen dispacher.js is its core file, its core is based on the event of publish/subscribe model completed, the core source code as follows:

classDispatcher{...//Register callback function,  Register(callback){    varId=_prefix+  This._lastid++;     This._callbacks[ID]=Callback;  }  The callback function registered in register is called when Dispatch is called.  Dispatch(payload){     This._startdispatching(payload);     for(varIdinch  This._callbacks){       This._invokecallback(ID);    }  }}

Review the previous goal: make the Store layer pure. A variable comments is defined to store the list data, and after understanding the core principles of Dispatcher, when invoking the dispatch (obj) method, the parameters can be passed to the pre-registered register function with the following code:

//Commentstore.js LetComments=[]ConstCommentstore= {  getcomment(){    returnComments}}Dispathcer.Register(action)= { //Call the Register function on the Dispatcher instance  Switch(Action.type){     Case ' get_list_success ': {Comments= Action.Comment    }  }})

And the functions in the action are as follows:

//Commentaction.jsConstCommentaction= {  getList(){    Fetch('./list.json ')      . Then(RES)= Res.JSON())      . Then(Result=        Dispathcer.Dispatch({ //Call the Dispatch function on the Dispatcher instance          type: ' get_list_success ',          Comment: result.Data        }))}}

But there seems to be something missing, and when GET_LIST_SUCCESS successful, it is found that the ability to call Commentstore.getcomment () Again is absent from the page, so referencing the event publish/Subscribe mode again, this time using the events module provided by node. JS, The Commentstore.js file is modified and the following code is modified:

 LetComments=[]ConstCommentstore= Object.Assign({}, Eventemitter.prototype, {  getcomment(){    returnComments},  Emitchange(){     This.Emit(' Change ')},  AddListener(callback){ //provided to the page component for use     This. on(' Change ',Callback}})Appdispathcer.Register(action)= {  Switch(Action.type){     Case ' get_list_success ': {Comments= Action.Comment      Commentstore.Emitchange()//With this line of code, there is the ability to notify the page to call Commentstore.getcomment again    }  }})

The final step is to integrate the store and action into the page with the following code:

classComponentlistextendsComponent{  Constructor(){    Super() This. State = {      Comment: Commentstore.getcomment()}  }  Componentdidmount(){    Commentstore.AddListener(()=  This.setState({ //Registration function, mentioned above, for store use      Comment: Commentstore.getcomment()}))}  Render(){    return(<Div>        { This. State.Comment.Map(r=          <P Key={R.ID}>{R.content}</p>        )}</div>)}}
Summary

Simply building an application with MVVM will find that the business logic and data are all coupled in the component, and the data and business logic are better separated after introducing the Flux schema pattern. But what are the drawbacks of using Flux? In the next "Chat Redux architecture mode" will be analyzed, see.

This case has been uploaded to Statemanage

Series blog, Welcome to Star

Explore the transformation from MVC to MVVM + Flux architecture Patterns

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.