How can I use ko.toJs method without computed prop

2019-02-08 07:22发布

问题:

I want to convert viewModel to Json object. But I don't want to map computed properties.

回答1:

Here are a few options, if you are going to convert it to JSON:

  1. if you are using constructor functions for your object, then you can override the .toJSON function to control which properties to output. Here is an article on it: http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html. Here is a sample: http://jsfiddle.net/rniemeyer/FE4HX/.

  2. in KO 2.1, when using ko.toJSON the second and third arguments are now passed to JSON.stringify. Here is some documentation on the arguments: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify. This means that you can pass the second argument (replacer) with either an array of properties to include or a function that processes the key/values. Here is the same sample using this technique: http://jsfiddle.net/rniemeyer/huyLe/.

  3. Another option that I use frequently, is to define computeds that you don't want in your JSON output as sub-observables. Observables are functions, which are objects, so you can actually define observables on observables. Like:

-

this.name = ko.observable("Bob");
this.name.formatted = ko.computed(...);

Now when converting to JSON, formatted will be naturally lost as name gets converted to its value. Here is the same sample again: http://jsfiddle.net/rniemeyer/peEGG/. Usually I use this when it is meta-data about an observable (isValid, isEditing, etc.).



回答2:

This will also work, it will just ignore anything with a 'mappedProperties' in it, for duck-type naysayers remember you shouldn't have mappedProperties as part of your code since you're using knockout. Therefore it should work.

/* Use this serializer function along with ko.toJS to produce clean JSON objects. */
ko.toJS2 = function (model)
{
     return JSON.parse(ko.toJSON(model, modelSerializer));
}

function modelSerializer(key, value)
{
if (isSerializable(value))
    return value;
else
    return;
}

function isSerializable(object) {
    if (object == null) return true;
    if (typeof object == 'function') return false;
    if (object.mappedProperties != null) return false;

    return true;
}

Usage:

var goodLookingJson = ko.toJS2(whateverModel);


标签: knockout.js