KnockoutJS - update observed value after applybindings

I need to update the observed value after creating the view model. In addition, I need to update the value directly in response to the event from the javascript control, without binding the object to the observable. I think it should be very simple, and that I just skip the correct syntax, but I just don't understand.

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 when starting JSFiddle, you will see that the error (s) has been caught.

AppViewModel.firstName('Todd'); 

Trying to update firstname in this way tells me that AppViewModel does not have a function called "firstName".

 AppViewModel().firstName('Todd'); 

This path tells me that firstName is undefined.

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

What am I missing?

+4
source share
2 answers

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

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

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

+7
source

You need to save the viewmodel variable in a variable and use this variable to change the name. I 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'); 
+1
source

Source: https://habr.com/ru/post/1491718/


All Articles