KnockoutJs dynamic Binding

KnockoutJs能够很方便地实现动态绑定,这种绑定是双向的,即对DOM数据源的修改会立即反映到DOM上。KnockoutJs是MVVM模式的实践者。例子如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>knockout demo</title>
    <script src="script/jquery-1.11.0.min.js"></script>
    <script src="script/knockout-3.3.0.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            var index = 1;

            $("#btnAdd").bind("click", function () {

                var item = {
                    Id: index + 1,
                    RequestType: "ResourceRequest",
                    RequestName: "VirtualMachine"
                };

                options.records.unshift(item);
                viewModelInstance.records(options.records);
                index++;

            });

            var options = {
                records: [
                    {
                        Id: "1",
                        RequestType: "BaseType", 
                        RequestName: "BaseName"
                    }
                ]
            };

            function viewModel(option) {
                this.records = ko.observableArray(option.records);
            };

            var viewModelInstance = new viewModel(options);
            ko.applyBindings(viewModelInstance);
        });
    </script>
</head>
<body>
    <table border="1px">
        <thead>
            <tr>
                <th><a>Id</a></th>
                <th><a>RequestType</a></th>
                <th><a>RequestName</a></th>
            </tr>
        </thead>
        <tbody data-bind="foreach: records">
            <tr>
                <td data-bind="text: Id"></td>
                <td data-bind="text: RequestType"></td>
                <td data-bind="text: RequestName"></td>
            </tr>
        </tbody>
    </table>
    <br/>
    <input id="btnAdd" type="button" value="add" />
</body>
</html>
效果:

点击add按钮,增加一条数据到数据源,列表会自动增加一行,确实非常方便!

你可能感兴趣的:(binding,MVVM,KnockoutJS)