I’m currently trying to learn Knockout.JS – I’m also relatively new to JavaScript itself.
There is an example on the website – http://knockoutjs.com/examples/clickCounter.html – that I am currently trying to wrap my head around.
I’ve put some comments into the code below with what I think is going on. And there is a question there about how the function is working.
It would be great if someone more experienced in Knockout could explain exactly what is going on there. Thanks.
(function() {
var clickCounterViewModel = function () {
// Here it looks like numberOfClicks is assigned the value 0 and wrapped in a ko.observable method
// that allows any changes of it to ripple throughout the application.
this.numberOfClicks = ko.observable(0);
// A function is created called registerClick and assigned to the ViewModel.
// The value of numberOfClicks is currently 0.
this.registerClick = function () {
// numberOfClicks is being used here as a method, but it was created as a property.
// It almost looks like I could write: this.numberOfClicks = this.numberOfClicks() + 1,
// however, that doesn't work. this.numberOfClicks is being passed into itself as an argument.
// Is this some sort of recursion? Can someone familiar with Knockout please explain how this is working?
this.numberOfClicks(this.numberOfClicks() + 1);
}
this.hasClickedTooManyTimes = ko.dependentObservable(function () {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new clickCounterViewModel());
});
I take it your confusion is with this line:
numberOfClicksis an observable, not a number, so+isn’t defined for it.When calling
numberOfClicks()that “unwraps” the observable into the underlying value (the number). I believe that calling an observable as a function with a single argument updates the value, sothis.numberOfClicks(1+1)would set the value ofnumberOfClicksto 2.