Showing knockouts - fromJS - failure on a simple example

I am trying to understand what I do not understand in the knockout mapping library. I have divided it into a simple example and still can cause it to fail (rather, not update the displayed variables) by calling fromJS .

What am I getting in this case fundamentally wrong?

 // Here my view model var ViewModel = function() { this.firstName = ko.observable('first'); this.lastName = ko.observable('last'); }; var myVM = new ViewModel(); ko.applyBindings(myVM); // Apply to Knockout (works) myVM.lastName('maiden name'); // Test an update (works) var newData = {firstName: 'new', lastName: 'person'}; // Try update the ViewModel ko.mapping.fromJS(newData, myVM); //(No update, or error) // Intended result - UI updates to 'new person' 

And the corresponding view:

 <div class='liveExample' > <p>First name: <input data-bind='value: firstName' /></p> <p>Last name: <input data-bind='value: lastName' /></p> </div> 

My Sample JS Script .

+6
source share
2 answers

ko.mapping.fromJS processes the parameters a little more complicated (see mine here) , so the second parameter is usually the display parameters:

 ko.mapping.fromJS(newData, {} /* mapping options */, myVM); 

JSFiddle demo.

+10
source

I found how to use only 2 data parameters.

Create a ViewModel as a source data mapping, then use ko.mapping.fromJS(data, ViewModel) .

UPDATED jsFiddle

Explanation

The knockout uses the mappingProperty = "__ko_mapping__" property to identify when data has been previously matched. If it is found, it will set the second parameter as the target (in this case, ViewModel).

Excerpt from the debug version of ko.mapping.js:

 var mappingProperty = "__ko_mapping__"; [...] if (arguments.length == 2) { if (arguments[1][mappingProperty]) { target = arguments[1]; } else { options = arguments[1]; } } 
+6
source

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


All Articles