knockOut:前端轻量级框架,类似于angular。

              功能:1.声明式绑定,        关键词:data-bind

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

                         2.依赖跟踪,           关键词:computed或pureComputed(用于数组)

                         3.UI界面自动刷新,关键词:类似于WPF模板

              语法:data-bind = "XX:oo"

                          XX表示标签的属性,可以是text,click.foreach,value等等

                          OO表示一个函数对象

             作用:通过XXOO将元素的属性或事件跟JS中的函数对象绑定

参考代码:

            

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    <title>myFirstDemo</title>
    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>><!--引入jquery核心库-->
    <script type="text/javascript" src="KnockOut-3.5.0.js"></script>><!--引入KnockOut核心库-->
</head>
<body>
    <table>
        <thead>
            <tr>
                <td>商品名称</td>
                <td>商品数量</td>
                <td>价格</td>
            </tr>
        </thead>
        <tbody data-bind="foreach:items">
            <tr>
                <td data-bind="text:product.name"></td><!--data-bind声明式绑定-->
                <td><select data-bind="options:[1,2,3,4,5,6],value:count"></select></td>
                <td data-bind="text:subTotal"></td>
                <td><a href="#" data-bind="click:$root.remove">remove</a></td>
            </tr>
        </tbody>
    </table>
    <h2>总价:<span data-bind="text:totalPrices"></span></h2>
    <button data-bind="click:addComputer">Add a Computer</button>

    <script type="text/javascript">
        var products = [{ name: "苹果笔记本", price: 98 },
                        { name: "惠普游戏本", price: 99 },
                        { name: "戴尔", price: 199 }];

        function order()
        {
            var self = this;
            //订单商品种类及数量
            this.items = ko.observableArray([new item(products[0], 2), new item(products[1], 2)]);

            //订单总价
            this.totalPrices = ko.pureComputed(//pureComputed或computed依赖追踪
                function ()
                {
                    var p = 0;
                    for (var i = 0; i < this.items().length; i++)
                    {
                        var item = self.items()[i];
                        p += item.product.price * item.count();
                    }
                    return p;
                }, self);
            //商品移除
            this.remove = function (item) { self.items.remove(item) };

            //商品添加
            this.addComputer = function () {
                self.items.push(new item(products[2], 1));
            };

        }

        function item(product, count)
        {
            this.product = product;
            this.count = ko.observable(count);//observable或observableArray(数组)界面自动刷新

            // 订单单项总价
            this.subTotal = ko.computed(function () {
                return this.count() * this.product.price;
            }, this);

        }
        ko.applyBindings(new order());
    </script>
</body>
</html>

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄