如何在敲除映射中使用 ko.toJs 方法而无需计算属性? [英] How can I use ko.toJs method without computed properties in knockout mapping?
问题描述
我想将 viewModel 转换为 Json 对象.但我不想映射计算属性.
I want to convert viewModel to Json object. But I don't want to map computed properties.
推荐答案
如果您要将其转换为 JSON,这里有几个选项:
Here are a few options, if you are going to convert it to JSON:
如果您为对象使用构造函数,则可以覆盖
.toJSON
函数来控制要输出的属性.这是一篇关于它的文章:http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html.这是一个示例:http://jsfiddle.net/rniemeyer/FE4HX/.
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/.
在 KO 2.1 中,当使用 ko.toJSON
时,第二个和第三个参数现在被传递给 JSON.stringify
.以下是有关参数的一些文档:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify.这意味着您可以使用要包含的属性数组或处理键/值的函数传递第二个参数 (replacer
).以下是使用此技术的相同示例:http://jsfiddle.net/rniemeyer/huyLe/.
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/.
我经常使用的另一个选项是将您不希望在 JSON 输出中的计算定义为子可观察对象.Observables 是函数,它们是对象,因此您实际上可以在 observables 上定义 observables.喜欢:
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(...);
现在当转换为 JSON 时,formatted
自然会丢失,因为 name
被转换为它的值.下面是相同的示例:http://jsfiddle.net/rniemeyer/peEGG/.通常我在它是关于可观察的元数据时使用它(isValid
、isEditing
等).
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.).
这篇关于如何在敲除映射中使用 ko.toJs 方法而无需计算属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!