码迷,mamicode.com
首页 > Web开发 > 详细

Knockoutjs 实践入门 (2) 绑定事件

时间:2015-05-04 21:37:30      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

Knockoutjs 绑定事件

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‘>&nbsp;</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

 技术分享

重置

技术分享

 

Knockoutjs 实践入门 (2) 绑定事件

标签:

原文地址:http://www.cnblogs.com/hbb0b0/p/4477124.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!