Knockoutjs 不仅支持UI 元素的属性绑定到model的属性,还支持UI 元素的事件绑定model的事件。
l click me button 每单击一次,计数器累加一次,并且把计数器次数显示到div中
l click me button 最大可单击3次,3次过后click me button 不能使用;单击次数达到3次时,显示提示信息,并且显示reset button
l reset button 单击后click me button 计数器清零,click me button 可用;提示信息与reset
button 消失
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/knockout-3.3.0.debug.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>You've clicked <span data-bind='text: numberOfClicks'> </span> times</div>
<!--button click 事件绑定model的onclick方法 -->
<!--button disable属性绑定hasClickedTooManyTimes属性 -->
<button data-bind='click: onClick, disable: hasClickedTooManyTimes'>Click me</button>
<!--div visible hasClickedTooManyTimes -->
<div data-bind='visible: hasClickedTooManyTimes'>
That's too many clicks! Please stop before you wear out your fingers.
<!--button click绑定resetClicks -->
<button data-bind='click: resetClicks'>Reset clicks</button>
</div>
</form>
<script type="text/javascript">
var model = function () {
//计数器
this.numberOfClicks = ko.observable(0);
//onclick方法
this.onClick = function () {
this.numberOfClicks(this.numberOfClicks() + 1);
};
//计数器重置
this.resetClicks = function () {
this.numberOfClicks(0);
};
//hasClickedTooManyTimes 属性
this.hasClickedTooManyTimes = ko.pureComputed(function () {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new model());
</script>
</body>
</html>
第一次click
第三次click
重置