Knockoutjs 实践入门 (3) 绑定数组

时间:2023-12-29 08:28:20

<form id="form1" runat="server">
        <div>
            <!--text value绑定model:itemToAdd,valueUpdate:更新数据绑定时机:按键时-->
            <!---如果不指定valueUpdate,使用默认更新数据绑定,经试验并不是onchange-->
            <input type="text"  data-bind='value:itemToAdd, valueUpdate: "afterkeydown"'/>
             <!--button enable:绑定itemToAdd,click事件绑定model.addItem方法-->
            <input type="button" value="Add" data-bind='enable:itemToAdd().length>0,click:addItem'  />

</div>
        <div>
            <!--select.options  绑定model.dataSource -->
            <select  multiple="multiple" style="width:200px" data-bind="options:dataSource"></select>
        </div>
    </form>
     <script type="text/javascript">
         var model = function (items) {
             //绑定数据源
             this.dataSource = ko.observableArray(items);
             //绑定observable:最终返回输入值,itemToAdd就是绑定输入值
             this.itemToAdd=ko.observable("");
             this.addItem = function () {
                 if (this.itemToAdd() != "") {
                     alert(this.itemToAdd());
                     //插入获取的输入值
                     this.dataSource.push(this.itemToAdd());
                     //输入值清空
                     this.itemToAdd("");
                 }
                 
                 //this 设置为model
             }.bind(this);
         };

//初始化model
         ko.applyBindings(new model(["aaa","bbb","ccc"]));
    </script>