I want to convert viewModel to Json object. But I don't want to map computed properties.
标签:
knockout.js
相关问题
- implementing html5 drag and drop photos with knock
- knockout checked binding doesn't update
- Knockout JS - Binding to array of observable Ints
- Knockout.js autocomplete bindingHandler [closed]
- Javascript in Edge only works with devtools open
相关文章
- Handle IE 9 & 10's clear button with Knockout
- jQuery Chosen doesn't update select options wh
- KnockoutJS property doesn't update when changi
- knockout.js - data-bind text default value
- Setting default values for computed Observable Kno
- Mapping: foreach binding work only the first time
- Knockout radio button binding with boolean
- Ajax Post and Redirect with Model Value MVC4
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 toJSON.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:
-
Now when converting to JSON,
formatted
will be naturally lost asname
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.).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.
Usage: