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?