Tony
Tony

Reputation: 12695

KnockoutJS - checkbox on check and computed function

I'm quite new in KnockoutJS and I have a 'simple' question - everytime I click on checkbox or label I see 1 in the console. But how exacly changeCheck 'knows' when it should be invoked ?

Is just return self.check(); informs knockoutJS to invoke changeCheck when check is changed ? I don't get it. Can somebody explain it for me, please ?

self.check = ko.observable(false);

self.changeCheck = ko.computed(function () {
    console.log(1);
    return self.check();
});

<input type="checkbox" id="myCB" data-bind="checked: check" />
<label for="myCB">lorem</label>

Upvotes: 1

Views: 1158

Answers (1)

Hans Roerdinkholder
Hans Roerdinkholder

Reputation: 3000

You are correct in your own attempt to answer the question. Knockout will analyze your computed observable to figure out what other observables are accessed. All these observables will be marked as dependencies for the computed observable (in other words, the computed observable will subscribe to changes of the observable). Whenever an observable changes, it will notify any subscribers of the changed value. For computed observables this means that recomputation will take place. A lot of what I just typed, and a lot of other useful information is provided in Knockout's documentation on computed observables, found here.

Upvotes: 1

Related Questions