Search code examples
knockout.jsknockout-mapping-plugin

What should you do in update callback of knockout.mapping in case options.data is null?


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.


Solution

  • 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.