简体   繁体   中英

Knockout Mapping doesn't work

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?

$.getJSON function works async so when you call console.log(self.form) mapping is not finished. To see your object in the console output move log operation into success function:

$.getJSON("x", function(allData) {
    if(){
        console.log("I'm here");
        ko.mapping.fromJSON(allData, {}, self.form);
        console.log(self.form);
    }else{
        // not relevant
    }
});

Try to use ko.mapping.fromJS instead of ko.mapping.fromJSON because allData is not string as fromJSON expected:

$.getJSON("x", function(allData) {
    if(){
        console.log("I'm here");
        ko.mapping.fromJS(allData, {}, self.form);
        console.log(self.form);
    }else{
        // not relevant
    }
});

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 with binding I won't attempt to show the form until it is loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM