Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ko.toJs method without computed properties in knockout mapping?

Tags:

knockout.js

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

like image 761
Oguz Karadenizli Avatar asked Jul 26 '12 15:07

Oguz Karadenizli


People also ask

What is Ko computed in knockout JS?

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.

What is Ko applyBindings?

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.


1 Answers

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

like image 128
RP Niemeyer Avatar answered Sep 27 '22 19:09

RP Niemeyer