Skip to content

Comment on Learn the MVVM pattern and knockout.js quickly with in-browser coding exercises

Comments

I'm a JS noob. Can someone explain to me why I have to add the fullName (ko.dependentObservable) after the declaration of the viewModel object? So, why does this:

var viewModel = { firstName: ko.observable("Bert"), lastName: ko.observable("Bertington"), fullName: ko.dependentObservable(function() { return this.firstName() + " " + this.lastName(); }, this) };

not work?

Because "this" as the second argument to the ko.dependentObservable doesn't refer to the viewModel object (it's still being declared), it refers to whatever the current context is. To check it, console.log or alert "this" inside the function and see what it's value is.

In other words, it could work, but would need the correct context instead of 'this'.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.