Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS - Update observable value after applybindings

Tags:

knockout.js

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?

like image 917
Todd Davis Avatar asked Jul 16 '13 19:07

Todd Davis


2 Answers

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/

like image 51
PaulProgrammer Avatar answered Sep 21 '22 00:09

PaulProgrammer


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');
like image 24
Skyp Avatar answered Sep 18 '22 00:09

Skyp