(四 )Knockout - ViewModel 的使用3 - 对象属性变化的实时更新

时间:2021-03-25 19:11:42

ko.observableArray()就可以自动检测属性,其实他只是监控对象,而不是对象中的属性

使用ko.observable()进行处理

DEMO1

实时更新属性

//定义user数据对象
var UserViewModel = function(id,name,score) {
var me = this;
me.id = id;
me.name =ko.observable(name); // 监控属性
me.score =ko.observable(score);
}
//定义ViewModel
var 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;
});
};
$(function () {
var vm = new ViewModel();
//预先添加一些数据
vm.users.push(new UserViewModel("d1", "rohelm", 121));
vm.users.push(new UserViewModel("d2", "walker", 125));
$("#btnAddUser").click(function () {
vm.users.push(new UserViewModel(
$("#u_id").val(),
$("#u_name").val(),
parseInt($("#u_score").val())));
});
$("#btnUpdateScore").click(function () {
vm.users()[vm.users().length-1].score(125).name("HelloWorld!");
});
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>
<input value="Update测试" id="btnUpdateScore" type="button" style="width:200px; background-color:#ff6a00;"/><br/>
</section>
</section>

DEMO2

通过属性控制html元素的显示、隐藏

var ViewModel = function() {
var me = this;
me.isVip = ko.observable(false); // 监控属性
me.username = ko.observable("walker_@@");
}
$(function () {
ko.applyBindings(new ViewModel());
});
<p>
<input id="isvip" type='checkbox' data-bind="checked: isVip" /><label for="isvip">是否是会员</label>
</p>
<p>
你的用户名是:
<input type='text' data-bind="value: username, enable: isVip,css: {account: username().indexOf('G')>-1}"/>
<span data-bind="visible: isVip">尊贵的会员欢迎你访问!</span>
</p>

解析:

view属性绑定,data-bind="checked:true/false",data-bind="visible:true/false"