Ray Cheng
Ray Cheng

Reputation: 12576

Why do I have to call applyBindings again after changing view model's property?

Here's the fiddle.

I have a view model where part of the data will be available after some user interaction.

Since the applyBindings is already called at document ready, why is it necessary to call again during a button click event?

HTML:

<p>first name:
    <input type="text" data-bind="value: ray.firstName" />
</p>
<p>last name:
    <input type="text" data-bind="value: ray.lastName" />
</p>
<p>first name:
    <input type="text" data-bind="value: joe.firstName" />
</p>
<p>last name:
    <input type="text" data-bind="value: joe.lastName" />
</p>

JS:

function person(firstNm, lastNm) {
    this.firstName = firstNm;
    this.lastName = lastNm;
}

function myApp() {
    this.ray = new person();
    this.joe = new person();
}

var app = new myApp();
app.ray = new person('ray', 'cheng');
ko.applyBindings(app);

$('#showName').on('click', function () {
    app.joe = new person('joe', 'public');
    ko.applyBindings(app); // <-- why is this needed since applyBindings already called above.
});

Upvotes: 1

Views: 348

Answers (1)

nemesv
nemesv

Reputation: 139758

You need to call applyBindings twice because you are not using observables. And without the observables Knockout is not able to track that your objects are changed so it cannot change the UI.

So your view model should look like this:

function app() {
    this.ray = ko.observable(new person());
    this.joe = ko.observable(new person());
}

And because ko.observable returns a function you need to set them like this:

app.ray(new person('ray', 'cheng'));
app.joe(new person('joe', 'public')); 

And to get the value in a data-bind expression you need to call the ko.observable without any argument like ray().firstName to get its value:

<input type="text" data-bind="value: ray().firstName" />

Demo JSFiddle.

Upvotes: 2

Related Questions