CKE
CKE

Reputation: 470

Knockout mappingOptions for ko.mapping.toJSON()-method

Problem

I'm trying to send a modified viewModel back to my server. Unfortunately I have to create my viewModel using ko.mapping.fromJSON() and some mappingOptions, which is working fine. Now I need an easy way to convert the created viewModel back to the original scheme.

Desired result

I want to convert this:

var myModel = {
    simpleProp: "test",
    complexProp: {
        simpleProp2: "test2",
        simpleProp3: "test3"
    }
};

into that (JS):

var myModel = {
    simpleProp: "test",
    modifiedToSimpleProWithNewName: "test2"
};

giving me this JSON:

{"simpleProp":"test","modifiedToSimplePropWithNewName": "test2"}

Attempts

I was thinking that, since ko.mapping.toJSON has a mapping parameter, it is as easy as creating another mapping for this method. But it seems like ko.mapping is actually ignoring my custom property creation:

var mappingOptions = {

    // ignored
    'simpleProp': {
        create: function (thing) {
            return "Changed simpleProps value";
        }
    },

    // working
    ignore: ["simpleProp3"]

};

Further Information

I've created a jsFiddle for you.

Please notice: I've simplified the example removing the model generation using fromJSON:

// created and modified by ko.mapping.fromJSON - with custom mapping!
var myModel = {
    simpleProp: "test",
    complexProp: {
        simpleProp2: "test2",
        simpleProp3: "test3"
    }
};

The result will be:

{"simpleProp":"test","complexProp":{"simpleProp2":"test2"}}

And as you can see, the ignore option will be applied, while the 'simpleProb'/create won't.

Any help is much appreciated. Thank you!

PS: I know that this mapping will not achive the desired result. It was just a "will 'simpleProp' be modified?"-test.

Upvotes: 4

Views: 2037

Answers (1)

lagerone
lagerone

Reputation: 1767

The mapping plugins toJSON method will, like the JSON.stringify function, check and use the return value of any toJSON method that might exist on the object before stringifying it to JSON.

Therefore you could do like this (updated jsfiddle):

var myModel = {
    simpleProp: "test",
    complexProp: {
        simpleProp2: "test2",
        simpleProp3: "test3"
    },
    toJSON: function () {
        return {
            simpleProp: this.simpleProp,
            complexProp: this.complexProp.simpleProp2
        };
    }
};

Just make the toJSON method format the object the way you want it to look and you're good to go.

Upvotes: 5

Related Questions