Understanding Flux Mechanisms and applications

Source: Internet
Author: User

Reactjs is the UI component framework introduced by Fackbook, the main feature is the introduction of the virtual DOM mechanism, and provides a very good UI component framework, the implementation of reusable Web front-end components can be possible.

But Reactjs is basically helping you to develop a reusable Web component framework, a lack of data bidirectional binding, dependency injection, binding, and a whole bunch of features.

And in front of the development, often need to provide a complete mechanism for DOM, data management, thus, various front-end MVVM framework is very popular, like Angularjs is a very popular MVVM framework.


Flux is an MVVM-like design pattern or architecture offered by Facebook, but Facebook only provides the design ideas and principles of flux, and Reactjs itself does not implement flux's complete library, which we can design

Ideas are self-fulfilling.

The design idea of flux is as follows:



The Flux architecture includes action (behavior), Dispatcher (scheduler), store (store), view (view), relatively common MVVM framework, the most characteristic of the flux design idea is that data is unidirectional flow, like Angularjs can be bound in two directions, This is not allowed in flux. Two-way binding is directly bound in the model and DOM, and looks cool when the page is more complex and more problematic.

About the specific principle of flux this article does not want to introduce carefully, see here


Here's a look at how to implement a flex application in detail with Reactjs.


1. Concept


Action: or action, such as adding an action, deleting an action, updating an action, is a bunch of functions.

Dispatcher (Scheduler): Responsible for the distribution scheduling of events. Facebook offers a ready-made dispatcher (called Flux.js,github) that can be used directly. Note that FLUX,JS is a module developed for Nodejs, if you want to have a browser to use it needs a little makeover.

Store: The place where the data is stored, or the equivalent of the model layer.

View: In the Reactjs is a variety of component.


2. Create Dispatcher (Scheduler)


Build a global scheduler.


  First introduced <script src= "Js/dispatcher.js" ></script>   dispatcher.js is changed from Flux,js to be used in the browser. var appdispatcher = new Dispatcher ();

3. Define Action Behavior

Defining a global variable to hold a variety of action,action is a normal JS function, as follows:

      var commentactions = {        create:function (author,text) {          ///to the dispatch center to register the issue          Appdispatcher.dispatch ({            ActionType: "Create",        //action type            author:author,            text:text          });        }      };

The main thing is the inside.
Appdispatcher.dispatch

This method requires you to provide a required actiontype parameter to illustrate the action. The other parameters are required for this action.

It can be understood that the method registers the action with the scheduler, and the scheduler can perform different store operations based on ActionType.

You can also add a variety of actions like delete,update. Similar to this:

var commentactions = {        create:function (author,text) {          ///to the dispatch center to register the issue          Appdispatcher.dispatch ({            ActionType: "Create",        //action type            author:author,            text:text          });        },        delete:function (index) {     <span style= "font-family:arial, Helvetica, Sans-serif;" >          appdispatcher.dispatch ({</span><pre name= "code" class= "JavaScript" >            actiontype: " Delete ",        //action type            author:author,            text:text          });
} };

4. Create Store

The store is a repository for storing data, you can manage your data as you want, or you can extract data from Ajax, such as the following example, which uses an array to hold the data.

     Store Data      var commentstore = {        items: [],        getall:function () {          return this.items;        },        GetItem: function (index) {          return this.items[index];        },        onchange:function (author,text) {          Console.log (" OnChange ");          This.items.push ({"Author": Author, "Text": text});        }      };

The Commentstore in the above example is a global variable.

The appdispatcher.register is then called to determine how the Commentstore operation is performed by passing the Dispacher incoming action parameter.

Appdispatcher.register (Action) {

        var text;        Switch (action.actiontype) {case          "create":            <pre name= "code" class= "JavaScript" >           commentstore< Span style= "font-family:arial, Helvetica, Sans-serif;" >.items.push ({"Author": Author, "Text": text});</span>
Trigger Change Event Commentstore.trigger (' Change ', action.author,action.text); Break } });
In this example, when a create action occurs, a data item is added and a change event is triggered.

The point is that when the action behavior occurs, the scheduler notifies the store to make data changes, and the process is done by the scheduler.

And after the data changes, how to notify the view update it?

The mechanism is through events and various callback, and in Flux.js's official Todo example, node's events module is used to register, BIND, and trigger events.

You can also manage a callback to handle events yourself.


In this article, I'm using a small event dispatcher called Microevent.js, using the following methods:

Microevent.mixin (Commentstore)

This method is executed to provide Commentstore with BIND, trigger, unbind and other methods, and provides an event distribution.

Add this sentence microevent.mixin (commentstore) to:

var commentstore = {    microevent.mixin (commentstore)} can then be <pre name= "code" class= "JavaScript" > Commentstore.bind ("Change", callback) binds a change event.
Commentstore.trigger ("Change", params) triggers a change event.

5. Notify View Changes


In the previous section, the store needed to trigger the corresponding event, and the event type could be defined by itself. So how does the view layer update?

The Componentdidmount event in Reactjs is the event that occurs after the component renders the dim, and it is clear that because Reactjs has the characteristics of the virtual DOM,

Update the event bindings to bind the change event above in the Componentdidmount event, like this:

var Comment = React.createclass ({<span style= "White-space:pre" ></span>onchange:function () {          Here you can do setstate operations        },        componentdidmount:function () {          <span style= "font-family:arial, Helvetica, Sans-serif; " >commentstore.bind ("Change", This.onchange)   #通过这里的侦听事件 </span>        },         Componentwillunmount: function () {        <pre name= "code" class= "JavaScript" ><span style= "font-family:arial, Helvetica, Sans-serif;" >                          commentstore.unbind ("Change") </span>
}})



6. Summary

It is clear that flux is just a design pattern, and that combining with REACTJS can provide best practices for large applications.





Understanding Flux Mechanisms and applications

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.