I want to convert viewModel to Json object. But I don't want to map computed properties.
ko. computed( evaluator [, targetObject, options] ) — This form supports the most common case of creating a computed observable. evaluator — A function that is used to evaluate the computed observable's current value. targetObject — If given, defines the value of this whenever KO invokes your callback functions.
For example, ko. applyBindings(myViewModel, document. getElementById('someElementId')) . This restricts the activation to the element with ID someElementId and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.
Here are a few options, if you are going to convert it to JSON:
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/.
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/.
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.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With