user1840885
user1840885

Reputation: 91

Trying to create multiple counters using Knockout.js

I can create one counter very easy with this example. How do I use this multiple times on one page?

<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>

Thanks!

Upvotes: 0

Views: 260

Answers (2)

Marc Bernstein
Marc Bernstein

Reputation: 110

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/

Upvotes: 1

Marc Bernstein
Marc Bernstein

Reputation: 110

I'm not sure I understand exactly what you mean by using this multiple times on one page? Do you want all of the instances to share the amount of times clicked or should they be independent of each other?

If they are just sharing it then you can just bind multiple elements to the same click event.

<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>

Upvotes: 0

Related Questions