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:
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.
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'.