Todd Davis
Todd Davis

Reputation: 6035

KnockoutJS - Update observable value after applybindings

I need to update an observable value after creating the view model. Furthermore, I need to update the value directly, in response to an event from a javascript control, without binding an object to that observable. I'm thinking this should be really easy, and that I'm just missing the correct syntax somehow, but I'm just not getting it.

I created a JSFiddle to illustrate what I'm trying to do. http://jsfiddle.net/toddhd/vwhqU/1/

If you press F12 and watch the console as you run the JSFiddle, you'll see the error(s) being caught.

AppViewModel.firstName('Todd');

Trying to update firstname this way tells me that AppViewModel has no function called "firstName".

AppViewModel().firstName('Todd');

This way tells me that firstName is undefined.

It may be that I have to call Apply Bindings again, but I don't really want to do that just to update a single value.

What am I missing?

Upvotes: 7

Views: 16144

Answers (2)

Skyp
Skyp

Reputation: 1197

You need to save your viewmodel in a variable and use this variable to change the first name. I have updated your jsfiddle : http://jsfiddle.net/vwhqU/3/

var vm = new AppViewModel();
ko.applyBindings(vm);

//I need to update first name directly later on, without a binding, in response to an event
vm.firstName('Todd');

Upvotes: 2

PaulProgrammer
PaulProgrammer

Reputation: 17700

You need to update the instance of the object, not the definition of the class.

var avm = new AppViewModel();
ko.applyBindings(avm);
avm.firstName('Todd');

http://jsfiddle.net/paulprogrammer/vwhqU/2/

Upvotes: 8

Related Questions