Domanda

This is 1 step further than this question.

I have a view model with nullable child property, like in before-mentioned question

var data =   [{ id: 0, child: { prop1 : 'a', prop2 : 'b' } }   //Child object has data
             ,{ id: 0, child: null } ];    // Child object is null

Now I want to use update callback of mapping plugin, and do this as follows:

var mappingOptions = {
    child: {
        create: function(options) {
            if (!options.data)
                return null;
            return ko.mapping.fromJS(options.data);
        }, 
        update: function(options) {
            if (!options.data)
                return null;

            // some update logic...

            return options.target; // this is also null in case options.data is null
        }
    }
} 

Now, when the options.data is null, I get an error in console "Uncaught TypeError: object is not a function", pointing to this code in mapping plugin:

...    
if (hasUpdateCallback()) {
    mappedRootObject(updateCallback(mappedRootObject));
}
...

where mappedRootObject is undefined.

So what should I return from update callback in case options.data is null?

JSFiddle Demo.

È stato utile?

Soluzione 2

Well, in case someone else will face the same issue, I've just updated ko.mapping plugin javascript as follows:

...    
if (hasUpdateCallback() && mappedRootObject) {
    mappedRootObject(updateCallback(mappedRootObject));
}
...

So, I check for existense of mappedRootObject before updating it. Although it worked fine, I've figured out a way, how to avoid update callback in my project at all, so this fix became useless to me, unfortunately.

Altri suggerimenti

For one, you never ran ko.applyBindings on your model.

http://jsfiddle.net/wEfWR/3/

ko.applyBindings(ko.mapping.fromJS(data))

Secondly, you're viewmodel object is not a function...nor is it really necessary.

New fiddle: http://jsfiddle.net/wEfWR/5/

Your 'child' object doesn't contain the data for child doesn't contain the child itself, so you need to make the update for your 'id' object instead.

update: function(options) {
    console.log(options);
    return options.data;
},
'child': {
    create: function(options) {
        if (!options.data)
            return null;
        return ko.mapping.fromJS(options.data);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top