javascript 设计模式-中介者模式 mediator (2) 购物车

* index.html




    
    shopping cart
    


购买手机加入购物车

* css/style.css

body {
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #212529;
    text-align: left;
}
input {outline: none;}
.feedback dl {
    display: block;
    position: relative;
    width: 200px;
    height: 1.5em;
}
.feedback dt {
    position: absolute;
    left: 0;
    width: 150px;
    text-align: right;
    white-space: nowrap;
}
.feedback dd {
    position: absolute;
    left: 120px;
}

.container {
    width: 100%;
    padding-left: 15px;
    padding-right: 15px;
    margin-right: auto;
    margin-left: auto;
}

@media (min-width: 576px) {
    .container {max-width: 540px;}
}

.row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-left: -15px;
    margin-right: -15px;
}

.form-group {
    margin-bottom: 15px;
}

.feedback {
    margin-left: 15px;
}

* js/index.js

/**
 * Created by Mch on 8/17/18.
 */
var getId = (function(func) {
    return function() {
        return func.apply(document, arguments);
    }
})(document.getElementById);

var goods = { // 手机库存
    "red|32G": 3,
    "red|16G": 0,
    "blue|32G": 1,
    "blue|16G": 6
};

var mediator = (function() {
    var colorSelect = getId("colorSelect"),
        numberInput = getId("numberInput"),
        colorInfo = getId("colorInfo"),
        numberInfo = getId("numberInfo"),
        nextBtn = getId("nextBtn");

// +memory
    var memorySelect = getId("memorySelect"),
        memoryInfo = getId("memoryInfo");

    return {
        change: function(obj) {
            var color = colorSelect.value,   // 颜色
                memory = memorySelect.value, // 内存
                number = numberInput.value, // 数量
                stock = goods[ color + '|' + memory];  // 颜色和内存对应的手机库存量

            // 如果改变的是选择颜色下拉框
            if (obj === colorSelect) {
                colorInfo.innerHTML = color;
            } else if (obj === memorySelect) {
                memoryInfo.innerHTML = memory;
            } else if (obj === numberInput) {
                numberInfo.innerHTML = number;
            }

            if (!color) {
                nextBtn.disabled = "disabled";
                nextBtn.innerHTML = "请选择手机颜色";
                return;
            }
            if (!memory) {
                nextBtn.disabled = "disabled";
                nextBtn.innerHTML = "请选择内存大小";
                return;
            }
            // 输入购买数量是否为正整数
            // if (Number.isInteger(number-0) && number > 0) {
            if ( ((number-0)|0) !== number-0) {
                nextBtn.disabled = true;
                nextBtn.innerHTML = "请输入正确的购买数量";
                return;
            }
            // 当前选择数量超过库存量
            if (number > stock) {
                nextBtn.disabled = "disabled";
                nextBtn.innerHTML = "库存不足";
                return;
            }
            nextBtn.disabled = false;
            nextBtn.innerHTML = "放入购物车";
        }
    }
})();

// 事件函数
[colorSelect, memorySelect, numberInput].forEach(function(dom) {
    dom.onchange = function() {
        mediator.change(this);
    }
});

var $ = (function() {
    function _xhr() {
        return new XMLHttpRequest();
    }
    function param(data) {
        return Object.keys(data).map(function(key) {
            return key + '=' + data[key];
        }).join('&');
    }
    function serialize(form) {
        var o = {};
        form.querySelectorAll("[name]").forEach(function(input) {
            o[input.name] = input.value;
        });
        // return Object.keys(o).map(function(prop) {return prop + "=" + o[prop];}).join('&');
        return o;
    }
    function ajax(o) {
        var request = _xhr(),
            type = o.type ? o.type : 'GET',
            url = o.url,
            success = o.success,
            dataType = o.dataType ? o.dataType : "html",
            data = o.data ? o.data : {};

        request.open(type, url, true);

        request.onload = function() {
            if (200 <= request.status && request.status < 400) {
                var resp = request.responseText;
                dataType === "json" ?
                    success(JSON.parse(resp)) : success(resp);
            } else {
                typeof o.fail === "function" && o.fail();
            }
        };
        request.onerror = function() {
            typeof o.error === "function" && o.error();
        };
        if (type.toUpperCase().localeCompare("POST")==0) {
            request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            request.send(param(data));
        } else {
            request.send();
        }
    }

    return {
        ajax: ajax,
        param: param,
        serialize: serialize
    }
})();
// php -S localhost:8080
document.forms[0].onsubmit = function(e) {
    e.preventDefault();
    var form = this, data = $.serialize(form);
    $.ajax({
        type: form.method,
        url: form.action,
        data: data,
        dataType: 'html',
        success: function (resp) {
            getId("J_response").innerHTML = resp;
        }
    })
};

* post.php

'; var_dump($_POST);
header('Content-Type: application/json; charset=utf-8');
$_POST['number'] = intval($_POST['number']);
echo json_encode($_POST);
$ php -S localhost:8080 #启动后台服务

* Run:

javascript 设计模式-中介者模式 mediator (2) 购物车_第1张图片

* http header:

  Connection: close;   # 服务器端主动关闭连接

你可能感兴趣的:(DesignPattern,javascript)