如何在剔除映射中使用没有计算属性的ko.toJs方法? [英] How can I use ko.toJs method without computed properties in knockout mapping?

查看:79
本文介绍了如何在剔除映射中使用没有计算属性的ko.toJs方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将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:

  1. 如果对对象使用构造函数,则可以覆盖.toJSON函数以控制要输出的属性.这是一篇文章: http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html .这是一个示例: http://jsfiddle.net/rniemeyer/FE4HX/.

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

现在使用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输出中使用的计算定义为子可观察项.可观察对象是函数,是对象,因此您实际上可以在可观察对象上定义可观察对象.像:

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时,随着name转换为其值,formatted自然会丢失.这又是相同的示例: http://jsfiddle.net/rniemeyer/peEGG/.通常,当它是有关可观察的元数据(isValidisEditing等)时,我会使用它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆