Avalonjs implement a simple shopping cart

Source: Internet
Author: User

Because recently in the shopping cart, and then we are using Avalon to implement some modules, so let its natural use of Avalon to achieve the shopping cart, now found that Avalon is still relatively powerful, greatly saving the amount of code.

Shopping cart generally has the function is to add and subtract quantity, select commodity, delete commodity and calculate amount, because Avalon has two-way binding function, so eliminate DOM operation, only need to complete the logic of the function, can be implemented in the following steps.

Runjs:http://runjs.cn/detail/1dnkgxom

1, the HTML structure of the page

This does not consider the good effect, so directly with the simplest HTML to achieve, mainly includes the Controller, list loop, amount display, simple code structure as follows

<body ms-controller= "Test" > <ul ms-visible= " Arr.length "> <li><input type=" checkbox "ms-click=" Checkall "ms-duplex-checked=" Checkallbool "/> Select all </li> <li ms-repeat= "arr" > <input type= "checkbox" ms-attr-value= "El.id" ms-duple X= "selected"/> {{el.text}} <input type= "text" name= "" ms-attr-value= "El.num" ms-on-in Put= "Changenum (EL)" > <a href= "javascript:;" ms-click= "Plus (EL)" > plus </a> <a h ref= "javascript:;" ms-click= "Minus (EL)" > minus </a> <a href= "javascript:;" ms-click= "Del (EL)" > Delete &l T;/a> <p> Price: {{El.price | currency}}</p> <p> amount: {{el.num*el.price | curre Ncy}}</p> </li> </ul> <p> Total amount: {{totals | currency}}</p> </body& gt; 

Here are all selected, add and subtract, delete several function events, the amount of the filter currency.


2, introduce avalon.js, define the model

The introduction of JS is necessary, then the introduction of Avalon.js can define the

var vm = avalon.define ({                $id: "Test"});

This defines a simple model, $id incoming is the controller's value, this example of the controller is written in the body, if you do not understand can go to see the official website.


3, define the shopping cart inside the goods

In the actual project, this is definitely obtained through the background, here for the demonstration directly defined, from the 1th HTML structure can be seen, here shopping cart goods with arr, so then define ARR, you can define

Arr: [  {    id:1,    num:1,    price:45.5,    text: ' Product 1 '  },  {    id:2,    num:1,    Price : 8.8,    text: ' Product 2 '  }

Here you define two to test, then you need a value to save the selected item ID, here you add a selected property to the model, the type is an array

Selected:[]


4. Define the model and method of selecting all

Shopping cart in the general have a full selection of functions, but the form of the expression is not the same, so you can define

Checkallbool:false,checkall:function () {      if (this.checked) {            var _arr = [];            Avalon.each (Vm.arr,function (index,item) {                 _arr[index] = item.id+ ";            });            vm.selected = _arr;      } else {           vm.selected=[];}      }

Through the Checkallbool property to implement and determine whether to select "All select", through the Checkall to select All or uncheck all, in fact, is to modify the selected property inside the model, if the selected is an empty array is not selected, If that needs to be checked just put the corresponding value in the selected array, because the checkbox is bound with Ms-duplex in HTML, and the selected property is bound.

4, the definition of addition, subtraction, deletion method

The addition and subtraction is primarily a quantitative change, and deletion is the need to remove the item directly from ARR (previously defined attribute)

Plus:function (EL) {   el.num++;   Vm.cal (); },minus:function (EL) {   if (el.num>1) {       el.num--;       Vm.cal ();   }},del:function (EL) {    vm.arr.remove (EL);},changenum:function (EL) {    var _value = This.value,        _reg =/^[1-9]\d?$/    ;    if (!_reg.test (_value)) {        this.value = 1;        El.num = 1;    } else{        el.num = _value;    }    Vm.cal ();}

Here is also a way to do when the input box is changed, here through the entry and exit objects to operate, you can see the first step of the HTML code, it is clear that both the change or the addition and subtraction are the last to execute vm.cal,vm.cal is calculated the total amount, will be explained below.

The method of addition and subtraction is very simple, mainly to modify the num attribute, Changenum increases the regular judgment, and determines whether the input is a number.


5. Define the total amount of the calculation

The way to calculate the total amount is simply to multiply the quantity of all selected items by the unit price, but there is another way to find out the corresponding product by the ID of the product, in order to calculate the amount of the item.

Total:0,cal:function () {    var _arr = This.arr,        _selected = this.selected,        i = 0,        _obj = ',        _prcie = 0< c5/>;    if (_selected.length) {for        (; i<_selected.length;i++) {            _obj = This.findbyid (_selected[i]) | | {};            if (_obj.price &&  _obj.num) {                  _prcie = _prcie + _obj.price * _obj.num;            }        }    }                        This.total = _prcie;},findbyid:function (ID) {    if (!id) return ';        var i=0,            _arr = This.arr,            _obj = ",            _id = parseint (id,10)        ;        for (; i<_arr.length;i++) {             if (_arr[i].id = = = _id) {                 _obj = _arr[i];}        }        return _obj;}



The main use of this is the loop, find the object of the product and then calculate the amount of the product added, the code is slightly longer.


6. Listening Properties

Need to listen to two properties, that is selected and ARR, monitoring selected is to keep abreast of the product is not fully selected, mainly by listening length. Monitoring arr is to determine if the product has not been deleted and if Arr's length changes, then the item has been deleted and the total amount needs to be recalculated.

vm.selected. $watch ("Length", function (n) {   Vm.checkallbool = n = = = Vm.arr.size ()   vm.cal ();}); Vm.arr. $watch ("Length", function (n) {   vm.cal ();});

Through the above steps analysis, you can understand the approximate implementation process, the following is the complete code.

<! DOCTYPE html>


With Avalon time soon, step-by-step, I hope to get a deeper understanding of the MVVM framework and apply more scenes in the days to come.

This article is also posted on my personal blog http://www.subying.com/archives/131.html





Avalonjs implement a simple shopping cart

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.