TimothyP
TimothyP

Reputation: 21755

Trying to understand why binding to a nested viewmodel fails

I have two ViewModels (although I like to think of the 'Person' ViewModel as the Model):

function Person() {
    var self = this;
    self.firstName = ko.observable("");
    self.lastName = ko.observable("");
}


function AppViewModel() {
    var self = this;
    self.admin = ko.observable(null);
    self.something = ko.observable("Hello World");
}

And then I set AppViewModel.admin to an instance of Person:

var viewModel = new AppViewModel();

var bob = new Person();
bob.firstName("Sponge");
bob.lastName("Bob");
viewModel.admin(bob);

ko.applyBindings(viewModel);

I then try to bind to it like this:

<p><strong data-bind="text: admin.firstName"></strong></p>
<p><strong data-bind="text: admin.lastName"></strong></p>
<p><strong data-bind="text: something"></strong></p>

I expected the output of this to be:

Sponge
Bob
Hello World

However that is not the case, instead the output is simply "Hello World"
(Obviously 'something' is just an observable of the AppViewModel, so that part works)

Can someone explain why it doesn't work and what I should be doing instead?

The full example on jsFiddle: http://fiddle.jshell.net/XRPAH/1/

Upvotes: 1

Views: 39

Answers (2)

ebram khalil
ebram khalil

Reputation: 8321

your object admin is observable so you need to access it using ()

for example :

<p><strong data-bind="text: admin().firstName"></strong></p>

and the same in the first line of your html it should be something like this

<p><strong data-bind="text: admin().firstName() + ' '+ admin().lastName()"></strong>
</p>

kindly check this Working Demo

Upvotes: 1

Niko
Niko

Reputation: 26730

"admin" is an observable, so you need to "invoke it" to access the contained value:

<p><strong data-bind="text: admin().firstName"></strong></p>

Actually, if you do

data-bind="text: something"

this is just shorthand for

data-bind="text: something()"

But if the observable is part of an expression such as admin.firstName, you need to explicitly write down the parentheses.

Upvotes: 2

Related Questions