0

I am learning Knockout.js and using with:binding to change the binding context as follows:

HTML:

<div id="wrap" data-bind="with: currentCat()">

    <h2 data-bind="text: name"></h2>
    <h3 data-bind="text: level"></h3>
    <div data-bind="text: count"></div>
    <img src="" alt="cute cat" data-bind="click: $parent.incrementCounter, attr: {src: imgSrc}">

</div>

Javascript:

var cat = function() {
    this.name = ko.observable("Fossie");
    this.imgSrc = ko.observable("--");
    this.count = ko.observable(0);
    this.nicknames = ko.observableArray(["Meow", "Johnny"]);
};

var viewModel = function() {

    this.currentCat = ko.observable(new cat());
    this.incrementCounter = function() {
        this.currentCat().count(this.currentCat().count() + 1);
    }

};
ko.applyBindings(new viewModel());

When I click on the image, I get this error:

Uncaught TypeError: this.currentCat is not a function

the same code worked without using with binding. Can anyone please explain what changed after I changed context?

software_writer
  • 3,941
  • 9
  • 38
  • 64

1 Answers1

3

this looses its context when used as an event handler. Use .bind

this.incrementCounter = function() {
    this.currentCat().count(this.currentCat().count() + 1);
}.bind(this);
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Wow, that solved the problem. Thank you, sir. Can you please elaborate what you meant by 'this looses its context when used as an event handler', and how binding fixed that problem? – software_writer Feb 20 '16 at 19:32
  • @akshayKhot http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – Daniel A. White Feb 20 '16 at 19:33
  • Thank you for the link. Before using `with`, I had `data-bind="click: incrementCounter` and the same JS without bind. It worked that time. How come `with` make it fail? – software_writer Feb 20 '16 at 19:39