0

通过这个例子,我可以很容易地创建一个计数器。如何在一页上多次使用它?

<div>
    You've clicked <span data-bind="text: numberOfClicks"></span> times
    <button data-bind="click: incrementClickCounter">Click me</button>
</div>

<script type="text/javascript">
    var viewModel = {
        numberOfClicks : ko.observable(0),
        incrementClickCounter : function() {
            var previousCount = this.numberOfClicks();
            this.numberOfClicks(previousCount + 1);
        }
    };
</script>

谢谢!

4

2 回答 2

1

In that case you can make use of javascript closures.

function Counter(){
    var self = this;
     self.numberOfClicks = ko.observable(0);
     self.incrementClickCounter = function() {
        self.numberOfClicks(self.numberOfClicks() + 1);
    };
}

var viewModel = {
     counter1: new Counter(),
     counter2: new Counter()
};

http://jsfiddle.net/marcandrew/wckE2/

于 2013-02-25T20:42:49.147 回答
0

我不确定我是否完全理解在一页上多次使用它的意思?您是否希望所有实例共享点击次数,还是应该相互独立?

如果他们只是共享它,那么您可以将多个元素绑定到同一个点击事件。

<div>
    You've clicked <span data-bind="text: numberOfClicks"></span> times
    <button data-bind="click: incrementClickCounter">Click me</button>
    <button data-bind="click: incrementClickCounter">Click me Too</button>
</div>
于 2013-02-25T19:08:57.973 回答