Development of front-end components based on unique state

Source: Internet
Author: User

Facebook's react framework presents an idea to render front-end components based on a unique state, what is the unique state, and what is the benefit of using a unique state rendering. I hope you see this article without any framework you can also write a front-end component that is based on a unique state rendering.

The development pattern of a component based on a unique state is that there is always only one copy of data within the component to represent the state of the component, and only this data is used when updating the component.

The benefits of this development model are mainly reflected in the following two areas

    • Reduce the connection of events to DOM elements
    • Easy to save and restore the state of a component
Reduce the connection of events to DOM elements

Let's take a look at the code that was written when we developed the page interaction logic:

    <span id="Click_count">0</span>    <input id="Color">    <button id="btn">Increasing</button>    <script type="Text/javascript">         function $(ID){            returndocument.getElementById (ID); }        $(' Color '). onkeyup = function(){            varCountdom = $ (' Click_count '); CountDom.style.backgroundColor = This. value; }         $(' btn '). onclick = function(){            varCountdom = $ (' Click_count ');varOldclickcount =parseint(countdom.innerhtml);varNewclickcount = oldclickcount+1;        countdom.innerhtml = Newclickcount; }</script>

If we use a unique state-based component development pattern later in the code

    <span id="Click_count">0</span>    <input id="Color">    <button id="btn">Increasing</button>    <script type="Text/javascript">         function $(ID){            returndocument.getElementById (ID); }//This is the only state of the component        varState = {count:0, Color:"'}; function render(){            varCountdom = $ (' Click_count ');            CountDom.style.backgroundColor = State.color;        countdom.innerhtml = State.count; }        $(' Color '). onkeyup = function(){State.color = This. value;        Render (); }         $(' btn '). onclick = function(){state.count++;        Render (); }</script>

With this relatively simple example we can see that the code is a lot more concise. But what good is it to write this, and we compare it in a graphic way

Legend of the first way

Legend of the second way

In this simple case, the feeling benefits are not too obvious, but we are much more complex in our usual business than this, there will be a lot of events and a lot of element, if we use the first way of writing, the legend is as follows

But if we use the second way of writing, the legend is as follows

If we have a M event, there are n element, if the first way of writing, there will be a total of (m*n) in the connection; if we use the second way of writing, there will be a M state connection in the event, from state to element there will be n links, There will be a total of (m+n) links; it's a lot easier to write.

facilitates the recording and recovery of component status

We are in the development of complex form applications, or the operation of more than the state of the scene, the page refresh needs to save the current state to Localstorate, server or file, the current page as a unique state to save.

The above interface, when we interact with the page, click Add, Previous, the next one of these buttons, all you need to do is update this unique state, save the current state, re-update the red area, refresh the page again will restore the original state, like the following code

Update status

        $(' Add '). onclick = function () { State. count++; State. Items.Push(' Item '+ State. Count); State.POS= State. Count;            SaveState ();        Render (); }$(' prev '). onclick = function () {if( State.POS==1)return; State.POS--;            SaveState ();        Render (); }$(' Next '). onclick = function () {if( State.POS== State. Count)return; State.POS++;            SaveState ();        Render (); }

Save state

After the state is serialized into a string, it is saved to Localstorage

    function saveState(){        localStorage.setItem(‘state‘,JSON.stringify(state));    }

Rendering components

Get the latest state, assemble an HTML string, and then redraw the entire component using innerHTML

     function render(){State =JSON. Parse (Localstorage.getitem (' state '))|| StatevarItems ="';varItemData = State.items; for(vari =0, L=itemdata.length; I < L; i++) {varBG ="';varOneitem = Itemdata[i];if(state.pos==i+1) {BG =' style= ' background-color:red "'; } items+=' <li '+bg+' > '+oneitem+' </li> '; };varHTML =' <span> number of lists '+state.count+' </span> '+' <ul> '+ items+' </ul> '+' <span> location of current entry '+state.pos+' </span> '; $(' container '). InnerHTML = html; }

Using innerHTML to redraw the components, each interaction will be re-rendered the whole area [no updated parts will be re-rendered], so that the number of pages reflow,repaint increase sharply, which will cause the page you performance degradation.

Is there any way to solve the problem? The answer, of course, is that we will focus on solving the problem in the next article.

Development of front-end components based on unique state

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.