user1840885
user1840885

Reputation: 91

Multiple "like" counters on the same page using knockout.js

I'm new to knockout and having problems creating multiple "like" button counters on the same page.

Here's my code.

        <ul>
            <li>
              <h4>Item 1</h4>
              <div><span data-bind='text: numberOfClicks1'>&nbsp;</span> likes</div>
              <button data-bind='click: registerClick'>Like?</button>
            </li>
            <li>
              <h4>Item 2</h4>
              <div><span data-bind='text: numberOfClicks2'>&nbsp;</span> likes</div>
              <button data-bind='click: registerClick'>Like?</button>
            </li>
        </ul>


<script type='text/javascript' src='js/knockout-2.2.1.js'></script>

<script type="text/javascript">
    var item1 = function() {
      this.numberOfClicks1 = ko.observable(0);
      this.registerClick = function() {
          this.numberOfClicks1(this.numberOfClicks1() + 1);
      };
    };

    ko.applyBindings(new item1());

    var item2 = function() {
      this.numberOfClicks2 = ko.observable(0);
      this.registerClick = function() {
          this.numberOfClicks2(this.numberOfClicks2() + 1);
      };
    };

    ko.applyBindings(new item2());
</script>

Not sure what I need to do?

Upvotes: 0

Views: 108

Answers (1)

Kyeotic
Kyeotic

Reputation: 19857

You're first problem is ko.applyBindings applies the given viewmodel to the entire page. If you want to control where the ViewModel is being applied, pass in a DOM node as the second parameter. You can see that with your code, in this fiddle.

ko.applyBindings(new item1(), document.getElementById("firstNode"));

However, this assumes you want to have multiple binding contexts and seperated viewmodels. Which brings us to your second problem: code duplication. You can make your code for liking things reusable by creating a Viewmodel for it.

var Likeable = function(name) {
    var self = this;
    self.name = ko.observable(name);
    self.likes = ko.observable(0);
    self.like = function() {
        self.likes(self.likes() + 1);
    };
};

With this reusable model, you can just make a collection of likeable objects, and bind a single context to it. You can see this in action in this fiddle

Upvotes: 1

Related Questions