Home Web Front-end JS Tutorial Avalonjs implements simple shopping cart function

Avalonjs implements simple shopping cart function

May 05, 2018 pm 04:08 PM
javascript shopping cart

This article mainly introduces Avalonjs to implement a simple shopping cart function, which has certain reference value. Now I share it with you. Friends in need can refer to it

avalon is the most powerful MVVM framework in China Recently, in the editor's shopping cart project, we used avalon to implement some modules, so it was natural to use avalon to implement the shopping cart. Next, through this article, I will share with you the example code of Avalonjs to implement a simple shopping cart function. Friends who need it can refer to it

. First, I will briefly introduce the concept of avalon

avalon is one of the most powerful MVVM frameworks in China. Although the Taobao KISSY team also developed two MVVM frameworks, they all came to nothing. There are few other MVVM frameworks. Only foreigners and idle architects like me have time to study this stuff. I predicted a long time ago that MVVM is the ultimate front-end solution. I have a deep understanding of Shanda Pass when I worked for Shanda Wireless. One business logic corresponds to more than ten different interfaces, and a layered architecture is essential. Therefore, two-way binding serves as an antidote, combined with the long-popular MVC framework, to derive the artifact of MVVM.

Because we have been working on a shopping cart recently, and we use avalon to implement some modules, so we naturally use avalon to implement the shopping cart. Currently, we find that avalon is relatively powerful, which greatly saves code. quantity.

The general functions of a shopping cart are to add and subtract quantities, select products, delete products and calculate amounts. Because avalon has a two-way binding function, it eliminates dom operations and only needs to complete the logic of the function. This can be achieved in the following steps.

1. Html structure of the page

The good effect is not considered here, so it is implemented directly with the simplest HTML, which mainly includes controllers and list loops. Amount display, the simple code structure is as follows

<body ms-controller="test">
 <ul ms-visible="arr.length">
  <li><input type="checkbox"
 ms-click="checkAll" ms-duplex-checked="checkAllbool"/>全选</li>
  <li ms-repeat="arr"
 >
  <input type="checkbox"
 ms-attr-value="el.id" ms-duplex="selected" />
  {{el.text}}
  <input type="text"
 name="" ms-attr-value="el.num" ms-on-input="changeNum(el)">
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
 ms-click="plus(el)">加</a>
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
 ms-click="minus(el)">减</a>
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
 ms-click="del(el)">删除</a>
  <p>单价:{{el.price
 | currency}}</p>
  <p>金额:{{el.num*el.price
 | currency}}</p>
  </li>
 </ul>
 <p>总金额:{{total
 | currency}}</p>
 </body>
Copy after login

There are several functional events such as all selection, addition, subtraction, and deletion. The amount uses the filter currency.

2. Introduce avalon.js and define the model

It is necessary to introduce js, then you can define it after introducing avalon.js

var vm
 = avalon.define({
  $id:
"test"
});
Copy after login

This way A simple model is defined. The $id passed in is the value of the controller. The controller in the example of this article is written in the body. If you don’t understand, you can check the official website.

3. Define the products in the shopping cart

In the actual project, this must be obtained through the background. Here it is directly defined for demonstration purposes, starting from the first You can see from the html structure of the click that the items in the shopping cart here use arr, so the next thing to define is arr, which can be defined like this

arr
 : [
 {
 id:1,
 num:1,
 price:45.5,
 text:&#39;商品1&#39;
 },
 {
 id:2,
 num:1,
 price:8.8,
 text:&#39;商品2&#39;
 }<span
 style="font-size:
 9pt; line-height: 1.5;">]</span>
Copy after login

Here we define two for testing, and then we need a value. Save the selected product id. Here, add a selected attribute to the model, the type is array

selected:[]

4. Define the model and method of selecting all

Generally, there is a function of selecting all in the shopping cart, but the form of expression is different, so it can be defined like this

checkAllbool
 : false,
checkAll
 : function()
 {
 if (this.checked)
 {
  var _arr
 = [];
  avalon.each(vm.arr,function(index,item){
   _arr[index]
 = item.id+&#39;&#39;;
  });
  vm.selected
 = _arr;
 }
else {
  vm.selected=[];
 }
}
Copy after login

Through the checkAllbool attribute, it is implemented and judged whether "select all" is selected, and through checkAll To select all or unselect all, it is actually to modify the selected attribute in the model. If selected is an empty array, no one is selected. If that needs to be selected, just put the corresponding value into the selected array, because in The checkbox in HTML is bound using ms-duplex, and the bound attribute is the selected attribute.

4. Methods of defining addition, subtraction, and deletion

Addition and subtraction are mainly changes in quantity, while deletion requires that the product be directly removed from arr (previously) Delete

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();
}
Copy after login

from the defined attributes) There is another method that is executed when the input box changes. Here, the operation is performed by entering and exiting the object. You can look at the html code in the first step and you will understand. Whether it is changes, additions or subtractions, vm.cal must be executed in the end. vm.cal calculates the total amount, which will be explained below.

The methods of addition and subtraction are very simple, just modify the num attribute. changeNum adds a regular judgment to determine whether the input is a number.

5. Define the calculation of the total amount

The method of calculating the total amount is very simple, that is, multiply the quantity of all selected products by the unit price and add them up, but here Another method is involved, which is to find the corresponding product through the product ID, so that the amount of the product can be calculated.

total:0,
cal:
function(){
 var _arr
 = this.arr,
 _selected
 = this.selected,
 i
 = 0,
 _obj
 = &#39;&#39;,
 _prcie
 = 0
 ;
 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 &#39;&#39;;
 var i=0,
  _arr
 = this.arr,
  _obj
 = &#39;&#39;,
  _id
 = parseInt(id,10)
 ;
  for(;i<_arr.length;i++){
  if(_arr[i].id
 === _id){
   _obj
 = _arr[i];
  }
 }
  return _obj;
}
Copy after login

The main thing used here is a loop. Find the object of the product and then calculate the amount of the product and add it up. The code is slightly longer.

6. Monitoring attributes

需要监听两个属性,那就是 selected 和 arr,监听 selected是为了随时了解商品有没有全选中,主要通过监听Length。监听arr是判断商品有没有被删除,如果arr的length改变,则表示商品有被删除,需要重新计算总金额。

vm.selected.$watch("length",
function(n)
 {
 vm.checkAllbool
 = n === vm.arr.size()
 vm.cal();
});
vm.arr.$watch("length",
function(n)
 {
 vm.cal();
});
Copy after login

通过上面的步骤分析,可以了解了大概的实现流程,下面是完整的代码。

 
 
 购物车
 
  
 
 <script>
  var
 vm = avalon.define({
  $id:
 "test",
  arr
 : [
   {
   id:1,
   num:1,
   price:45.5,
   text:&#39;商品1&#39;
   },
   {
   id:2,
   num:1,
   price:8.8,
   text:&#39;商品2&#39;
   }
  ],
  selected
 : ["1"],
  checkAllbool
 : false,
  checkAll
 : function() {
   if
 (this.checked) {
   var
 _arr = [];
   avalon.each(vm.arr,function(index,item){
    _arr[index]
 = item.id+&#39;&#39;;
   });
   vm.selected
 = _arr;
   }
 else {
   vm.selected=[];
   }
  },
  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();
  },
  total:0,
  cal:
 function(){
   var
 _arr = this.arr,
   _selected
 = this.selected,
   i
 = 0,
   _obj
 = &#39;&#39;,
   _prcie
 = 0
   ;
   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 &#39;&#39;;
   var
 i=0,
   _arr
 = this.arr,
   _obj
 = &#39;&#39;,
   _id
 = parseInt(id,10)
   ;
   for(;i<_arr.length;i++){
   if(_arr[i].id
 === _id){
    _obj
 = _arr[i];
   }
   }
   return
 _obj;
  }
  });
  vm.selected.$watch("length",
 function(n) {
  vm.checkAllbool
 = n === vm.arr.size()
  vm.cal();
  });
  vm.arr.$watch("length",
 function(n) {
  vm.cal();
  });
  vm.cal();
 </script>
 
 <body ms-controller="test">
 <ul ms-visible="arr.length">
  <li><input type="checkbox"
 ms-click="checkAll" ms-duplex-checked="checkAllbool"/>全选</li>
  <li ms-repeat="arr"
 >
  <input type="checkbox"
 ms-attr-value="el.id" ms-duplex="selected" />
  {{el.text}}
  <input type="text"
 name="" ms-attr-value="el.num" ms-on-input="changeNum(el)">
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
 ms-click="plus(el)">加</a>
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
 ms-click="minus(el)">减</a>
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
 ms-click="del(el)">删除</a>
  <p>单价:{{el.price
 | currency}}</p>
  <p>金额:{{el.num*el.price
 | currency}}</p>
  </li>
 </ul>
 <p>总金额:{{total
 | currency}}</p>
 </body>
Copy after login

    用avalon时间还不久,一步步来,希望能更深入了解mvvm框架,在后面的日子里应用更多的场景。


The above is the detailed content of Avalonjs implements simple shopping cart function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Mar 15, 2024 pm 12:27 PM

Practical tutorial: Detailed explanation of the shopping cart function with PHP and MySQL. The shopping cart function is one of the common functions in website development. Through the shopping cart, users can easily add the goods they want to buy to the shopping cart, and then proceed with settlement and payment. In this article, we will detail how to implement a simple shopping cart function using PHP and MySQL and provide specific code examples. To create a database and data table, you first need to create a data table in the MySQL database to store product information. The following is a simple data table

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles