AnyOne
AnyOne

Reputation: 931

ko.dependentObservable how this method understand dependencies cleverly?

I am playing with knockoutjs with their samples and i have been edited orginal code bit of which is at below. fullName property assigned as dependentObservable and this method definitely knows which dependencies inside fullName method so fullName method works only if dependencies changed.

If i remove this.LastName() from fullName method so changing lastName property does not cause invoke fullName method.

I wonder how this is happening.

var viewModel = {
    firstName: ko.observable("Bert"),
    lastName: ko.observable("Bertington")
};

viewModel.fullName = ko.dependentObservable(function() {
    alert('worked');
    return this.firstName() + " "+ this.lastName() ;
}, viewModel);


// Activates knockout.js
ko.applyBindings(viewModel);

Upvotes: 0

Views: 2168

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

There is a dependency tracking mechanism in Knockout that is used while evaluating dependentObservables. The key is that accessing an observable has to go through a function ( you have to call this.firstName()). Along with returning the firstName, Knockout adds the dependentObservable as a subscriber to firstName. When firstName is updated (which again has to go through the function), then all subscribers are notified.

Also, these dependencies are re-evaluated each time that a dependentObservable is evaluated, so the dependencies can actually change over time for a dependentObservable.

Upvotes: 4

Related Questions