Pushok icon

Bucket test script

Pushok | PRO | 11/03/15 05:55:23 PM UTC | 0 ⭐ | 504 👁️ | Never ⏰ | []
JavaScript |

1.53 KB

|

None

|

0 👍

/

0 👎

var bucket = new Map();
 
function Book(name1, price1){
    this.name = name1;
    this.price = price1;
    this.count = 1;
    
    this.getName = function(){return this.name;};
    this.getPrice = function(){return this.price;};
    this.inc = function(){return ++this.count;};
    this.getCount = function(){return this.count;};
}
 
 
function updateBucketForm(){
    var form = $("#bucket");
    form.attr("style", "list-style-type: none;");
 
    if(bucket.length == 0){
        form.empty();
        form.append("<h1>Ваша корзина пуста</h1>");
    }
    else{
        form.empty();
        var sum = 0;
        
        bucket.forEach(function(book){
            form.append("<li><h3>"+book.getName()+" (" + book.getCount() + " шт.)</h3></li>");
            sum += +book.getPrice()*book.getCount();
        })
        
        form.append("<li><h3>Общая сумма товаров: " + sum + " руб.<h3></li>");
        form.append("<button id=\"clean-bucket\">Очистить корзину</button>");
        $("#clean-bucket").click(function(){
            bucket = new Map();
            updateBucketForm();
        })
    }
}
 
$(document).ready( function(){
    updateBucketForm();
    
    $('.thumbnail').each(function(index) {
        $(this).find("button").click(function(){
            var book_name = $(this).parent().attr("data-name");
            var book_price = $(this).parent().attr("data-price");
            
            var value = bucket.get(book_name);
            if(typeof value != "undefined"){
                value.inc();
                bucket.set(book_name, value);
            }
            else{
                bucket.set(book_name, new Book(book_name, book_price));
            }
            
            updateBucketForm();
        })
    })
})

Comments