Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  134] [ 7]  / answers: 1 / hits: 19574  / 10 Years ago, fri, february 21, 2014, 12:00:00

I have just started trying knockout.js. The ko.mapping offers a nifty way to get and map data from server. However I am unable to get the mapping to work.



I have a simple model:



//var helloWorldModel;
var helloWorldModel = {
name: ko.observable('Default Name'),
message: ko.observable('Hello World Default')
};


$(document).ready(function() {
ko.applyBindings(helloWorldModel);
//a button on the form when clicked calls a server class
//to get json output
$('#CallServerButton').click(getDataFromServer);
});

function getDataFromServer() {
$.getJSON(HelloSpring/SayJsonHello/chicken.json, function(data) {
mapServerData(data);
});
}

function mapServerData(serverData) {
helloWorldModel = ko.mapping.fromJS(serverData, helloWorldModel);
alert(JSON.stringify(serverData));
}


The helloWorldModel has only 2 attributes - exactly the same thing I return from the server. The alert in mapServerData shows -



{name:chicken,message:JSON hello world}


I have looked up other posts regarding similar problem, but none of them seemed to be solve this issue. Maybe I am missing something very basic - wondering if anyone can point it out.



Also note if I do not declare the model upfront and use



 helloWorldModel = ko.mapping.fromJS(serverData);


it is mapping the data to my form correctly.


More From » knockout.js

 Answers
19

From Richard's reply and then a little more investigation into this I think that the way I was initializing the model is incorrect. I guess that one cannot use an existing view model and then expect it to work with mapper plugin. So instead you initialize view model with raw JSON data using the ko.mapping.fromJS:



var helloWorldModel;

$(document).ready(function() {
var defaultData = {
name: 'Default Name',
message: 'Hello World Default'
};

helloWorldModel = ko.mapping.fromJS(defaultData);
ko.applyBindings(helloWorldModel);
$('#CallServerButton').click(getDataFromServer);
});

function getDataFromServer() {
$.getJSON(HelloSpring/SayJsonHello/chicken.json, function(data) {
mapServerData(data);
});
}

function mapServerData(serverData) {
alert(JSON.stringify(serverData));
ko.mapping.fromJS(serverData, helloWorldModel);
}


This code works and provides the expected behavior


[#72403] Wednesday, February 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;