I’m having troubles using Knockout Mapping.
I have a FormBuilderViewModel, containing a bunch of functions including loading and saving data. The first line (after self = this) is the following:
this.form = ko.mapping.fromJS({blueprint_identifier: undefined, name: undefined, description: undefined, pages : []})
I initialise ‘this.form’ with 3 meta variables and 1 array.
Then, I load the data (also in FormBuilderViewModel):
ko.mapping.fromJSON(allData, {}, self.form);
The variable allData comes from the AJAX request and contains exactly this:
{"blueprint_identifier":1347437911,"name":"test","description":"test","pages":[]}
The problem is: the loaded JSON never appears on my page. The output of console.log(this.form) AFTER loading the data is empty. Here’s the entire script (apart from the functions etc.):
var FormBuilderViewModel = function(data){
var self = this;
this.form = ko.mapping.fromJS({
blueprint_identifier: undefined,
name: undefined,
description: undefined,
pages : []
})
$.getJSON("x", function(allData) {
if(){
console.log("I'm here");
ko.mapping.fromJSON(allData, {}, self.form);
}else{
// not relevant
}
});
console.log(self.form);
};
Output is ‘I’m here’ (so we get to the loading point), then the empty ‘form’ object.
What am I missing here?
Here is a functioning fiddle that does what you are looking for:
http://jsfiddle.net/jearles/Cm4xS/
I initialize form with an empty observable, and then load it when the AJAX call returns. By using the
withbinding I won’t attempt to show the form until it is loaded.