Data-driven page patterns in JavaScript

Source: Internet
Author: User

The previous time has been thinking about the meaning of front-end MVC. The topic is the same, but the way MVC is used gives me an interesting idea of managing data-data management and data-driven pages. Our previous thinking has been the event-driven page, where event-driven pages are logical and save code. But often the code structure is very loose, this loose is not what everyone expected loose coupling, but a kind of messy feeling, later in a code, I tried to use data to drive the page, feel good, logic is relatively simple. Here is a simple way to share my thoughts.

    1. I have an electronic store and I need a shopping cart feature.
    2. I want the shopping cart to handle the logic at the front. And backstage just saves the user order.

The following is the format of the data saved by the order.

var orderlist = {    0:{        ' id ': ' 12653 ',        ' productName ': ' Kindle fire ',        ' price ': 790,        ' Amount ': 2,        ' Discount ': 0.75    },    1:{        ' id ': ' 2653 ',        ' productName ': ' IPad ',        ' price ': 2790,        ' amount ': 10,        ' discount ': 0.70    },    2:{        ' id ': ' 653 ',        ' productName ': ' Mac ',        ' price ': 7900,        ' Amount ': 1,        ' discount ': 0.95    },    Length:3,    subscriberid: ' 254 ',    totalprice:0}

First we use a data manager to maintain the user's order data, we design it as a single mode.

var shppingcar = function () {    var orderlist = {}    this.add = function (obj) {        //Add a purchase data    }    This.remove = function (obj) {        //delete a purchase data    }    this.gettotilprice = function (obj) {        //Get Total Price    }    this.update = function (obj) {        //update purchase quantity    }    This.getorder = function () {        return orderlist;    }}

This looks like the data structure is clear, and the code organization seems good. Next comes the operation of our Dom section.

var order = new Shppingcar (), orderlist = Order.getorder (), var htmlmanager = function (list) {    //render page with orderlist data. }//First Initialize data Htmlmanager ();//Add a data Orderlist.add ({}); orderlist = Order.getorder (); Htmlmanager (orderlist);// Delete a data orderlist.add (ID); orderlist = Order.getorder (); Htmlmanager (orderlist);//Update a data orderlist.update (ID); o Rderlist = Order.getorder (); Htmlmanager (orderlist);

Every time we do a data operation, we have to update the data once. We have no way to change this fact, because the fact is that data changes, we must modify the page.

Perhaps you have a better idea, that is, instead of orderlist rendering the DOM, use a callback function to handle it. Then the code becomes

This.add = function (OBJ,FN) {    //Add a purchase data    if (FN) {        fn ();    }} You can do this using Orderlist.add ({},function () {    //parse data once, generate a DOM structure, insert    /change Total price});

This also means that you have to write different callback functions for deleting, adding, and updating separately, and it doesn't seem like a very good idea.

Back to the previous code, we only need to make a small change, we can use the data changes to drive our page update, which is also a pseudo-observer pattern. The idea is that the data is updated and I want to re-render the page.

var shppingcar = function () {    var orderlist = {}    ///We have added a private method to Shppingcar, and automatically updates the page for us when the data changes.    var rander = function () {    }    this.add = function (obj) {        //Add a purchase data        Rander ();    }    This.remove = function (obj) {        //delete a purchase data        Rander ();    }    This.gettotilprice = function (obj) {        //Get Total Price        rander ();    }    This.update = function (obj) {        //update purchase Quantity        Rander ();    }    This.getorder = function () {        return orderlist;    }}

So we can do that when we use it.

var orderlist = new Shppingcar ();//Add a data Orderlist.add ({});

We just change the external rendering function to the private method of the shopping Cart object, and then call this private method when the data is changed, so we can save the method of calling an update page again every time the data is updated. Although the amount of code reduction is not many, but to encapsulate all the content of the outside call seems to be more hassle-saving.

As for deleting data and updating data, we don't even need to define it externally, bind the event directly to the element when the page is rendered (the following example code I implemented a delete binding, the ability to modify the number of items are interested in their own implementation. )

I don't know if it makes sense to do so, I hope you shoot.

The attached test code is as follows.

var shppingcar = function () {//We design the data in such a format as var orderlist = {length:0, SubscriberId: ' 254 ', t    otalprice:0}            Some tool methods//through the book ID is currently the first few data var GetItemByID = function (ID) {for (var i = 0; i < orderlist.length; i++) {            if (orderlist[i].id = = ID) {return i;        }}}//Reorganize data into standard format var refreshdata = function () {var o = {},n = [];            for (var key in orderlist) {var k = number (key);            if (!isnan (k)) {N.push (Orderlist[key]);            }else{O[key] = Orderlist[key];        }} for (var i = 0; i < n.length; i++) {o[i] = N[i];    } orderlist = O;        }//Calculate Total price var updatetotilprice = function () {var totalprice = 0; for (var i = 0; i < orderlist.length; i++) {Totalprice +=orderlist[i].price*orderlist[i].discount*orderlist        [I].amount; } return TotalpriCe    };        Render page var htmlmanager = function () {var items = "<ul>";                    for (Var i=0;i<orderlist.length;i++) {Items + = "<li><span> Item No:" +orderlist[i].id + "</span> <span> Product Name:" +orderlist[i].productname + "</span> <span> commodity Price:" +ord Erlist[i].price + "</span> <span> order Quantity:" +orderlist[i].amount + "&LT;/SPAN&G T <span> Merchandise Discount: "+orderlist[i].discount+" </span> "+" <a data-id= "+orderlist[i].id+" Href= ' # # # '        > Delete </a></li> "} Items + =" </ul> ";        items+= "The total price of goods is" + Orderlist.totalprice + "Yuan";        document.getElementsByTagName ("Body") [0].innerhtml = (items);        Binding Delete event var delbtns = document.getElementsByTagName ("a");                    for (var j = 0; J < Delbtns.length; J + +) {(function (k) {Delbtns[k].onclick = function () { RemoveDelbtns[k].getattribute (' Data-id '));                return false;    }}) (j)}//binding modified number of events};        Delete a data var remove = function (id) {var item = GetItemByID (ID);        Delete Orderlist[item];        Orderlist.length-=1;        RefreshData ();        Orderlist.totalprice = Updatetotilprice ();    Htmlmanager ();        }//update number of items var update = function (Id,amount) {//todo: Update purchase quantity Orderlist.totalprice = Updatetotilprice ();    Htmlmanager (); }//external interface method, one can add a purchase data, one to get the current shopping cart all the data This.add = function (obj) {//todo: Verify that the incoming data is legitimate//todo: here to determine whether the        The product exists and, if present, calls the Updata method.        Orderlist[orderlist.length] = obj;        if (Orderlist[orderlist.length]) {orderlist.length +=1;        } Orderlist.totalprice = Updatetotilprice ();    Htmlmanager ();    } This.getorder = function () {return orderlist; };};/ /How to use: var orderlist = new Shppingcar (); Orderlist.add ({' id ': ' 6530 ',   ' ProductName ': ' Mac mini-0 ', ' price ': 4900, ' Amount ': 4, ' Discount ': 0.90} ' Orderlist.add ({' id ': ' 65301 ', ' PR Oductname ': ' Mac mini-1 ', ' price ':, ' Amount ': 4, ' Discount ': 0.90} ' Document.onclick = function () {Console.lo G (Orderlist.getorder ());};

Data-driven page patterns in JavaScript

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.