首页 > 网站 > WEB开发 > 正文

(三)Knockout

2024-04-27 14:13:54
字体:
来源:转载
供稿:网友

(三)Knockout - ViewModel 的使用2 - select、list 应用

select下拉菜单

<select>常用的data-bind参数:

options :

指向数组或ko.observableArray(),KO会将数组元素转换为下拉选项。如果是ko.observableArray(),当动态增加或移除阵列元素时,下拉选项也会马上跟着增减。

optionsText, optionsValue :

用来产生下拉选项的数组元素可以是具有多个属性的javaScript对象,通过optionText, optionValue设定属性名称字符串,我们可以指定用哪个属性当成<option>的文字内容,哪个属性当成value 。

value :

指向ViewModel的特定属性,属性一般以ko.observable()声明。如此当下拉菜单选取新值,所选的<option> value值会更新到ViewModel属性上;而一旦该属性被程序修改或因使用者输入改变,下拉菜单也会自动切到新值对应的<option >选项上。

selectedOptions :

针对可多选( multiple )的<select>,selectedOptions可绑定到ko.observableArray()类型属性,该数组使会即时反应使用者所选取的项目集合;而变更该obervableArray数组的元素项目,也会立刻变更对应option的selected状态。

DEMO1

使用静态数据绑定

<select data-bind ="options:selectOptions, optionsText: 'name', optionsValue: 'id', value:result"></select><br/>排行:<span data-bind ="text:result" ></span ><br/><input type ="button"  value ="Third"  data-bind ="click:changeToYoung"/>
var MyViewModel = function() {    var me = this;    me.selectOptions = [            {name:"First",id:1},            {name:"Second",id:2},            {name:"Third",id:3}    ];    me.result = ko.observable(2); //只能检测 value    me.changeToYoung = function(){        me.result(3);  //ko.observable()声明的属性,使用PRopName("...")方式改变其值,才能通知相关UI产生联动效果    }}ko.applyBindings(new MyViewModel());

解析:

- ViewModel定义了selectOptions数组(假设选项不会动态变化,故用一般数组即可,不用ko.observableArray),数组元素对象各有t、v两个属性分别当做<option>的文字跟值,而下拉菜单的选取结果要反应到result这个ko.observable()属性上

- 为了观察选取结果,再增加一个<span data-bind="text: result">即时反应result内容。

-声明一个chageToPhone()函数,将result的值强制指定为"Third"。

DMEO2

动态数据绑定

在<select> data-bind的options选项如果绑定到ko.observableArray(),就可以动态新增选项效果,也就是可以利用其完成常见的级联效果的。

var ViewModel = function() {   var me = this;   //使用observableArray进行绑定可以动态变更option选项   me.selectOptions = ko.observableArray([        { "text": "请选择", "value": "0" }   ]);   me.result = ko.observable("0");//添加result监控属性,初始绑定值为0}
var vm = new ViewModel();ko.applyBindings(vm);$("#btnAddItem").click(function () {   vm.selectOptions.push({       "text": $("#txtOptText").val(),       "value": $("#txtOptValue").val()   });});
<select style="background-color:ActiveCaption;width:100px"  data-bind="options: selectOptions, optionsText: 'text', optionsValue: 'value', value: result"></select>Value=<span data-bind=" text: result"></span><div> Text: <input id="txtOptText" value="选项1"/></div><div>Value: <input id="txtOptValue" value="1" /></div><input type="button" value="新增选项" id='btnAddItem' />

列表list

在某个容器元素(例如: div, ul, tbody... )声明data-bind="foreach: arrayPropName",就可以指定KO将容器内的子元素模板(Template)就会对数组对象的数据自动循环遍历

DEMO3

实现用户列表的展示,可移除某用户

- 定义数据对象

//定义user数据对象var UserViewModel = function(id,name,score) {    var me = this;    me.id = id;    me.name = name;    me.score = score;}

- 定义ViewModel对象

//定义ViewModelvar ViewModel = function() {    var me = this;    me.users = ko.observableArray();//添加动态监视数组对象    me.removeUser = function (user) {        me.users.remove(user);    }    me.totalscore = ko.computed(function () {          var total = 0;        $.each(me.users(), function (i, u) {            total += u.score;        })        return total;    });};

- 使用ViewModel

var vm = new ViewModel();//预先添加一些数据vm.users.push(new UserViewModel("d1", "rohelm", 121));vm.users.push(new UserViewModel("d2", "halower", 125));$("#btnAddUser").click(function () {     vm.users.push(new UserViewModel(        $("#u_id").val(),        $("#u_name").val(),        parseInt($("#u_score").val())));});ko.applyBindings(vm);
<section style="margin:250px">    <section>     ID<input type="text" id="u_id" style="width:30px">     Name<input type="text" id="u_name" style="width:30px">     Score<input type="text" id="u_score" style="width:30px"><br/>     <input  value="Add" id="btnAddUser" type="button" style="width:200px; background-color:#ff6a00;"/><br/>       共 <span data-bind="text: users().length"></span> 条--------------合计 <span data-bind="text: totalscore"></span> 分    </section>    <section>       <table>        <thead>            <tr><th>ID</th><th>Name</th><th>Score </th><th>Option</th></tr>        </thead>        <tbody  data-bind="foreach: users">            <tr>                <td><span data-bind="text: id"></span></td>                <td><span data-bind="text: name"></span></td>                <td><span data-bind="text: score"></span></td>                <td><a href='#' data-bind="click: $root.removeUser">Remove</a></td>            </tr>        </tbody>    </table>    </section></section>

解析:

有一个数组属性—users,使用data-bind="foreach: users" 绑定到table上,每条数据绑定各属性并展示

•data-bind="click: $root.removeUser"$root是一个特殊变量,会指向ViewModel个体。在这里必须加上的原因是我们在ViewModel定义了remoteUser方法

ViewModel中,当添加user,便会计算totalScore


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表