如何从Knockoutjs中排除某些属性toJS() [英] How to exclude certain properties from Knockoutjs toJS()

查看:98
本文介绍了如何从Knockoutjs中排除某些属性toJS()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

var model = {
   A: 'One',
   B: 'Two',
   C: 'Three'
};

我将各种UI元素绑定到这些字段,效果很好。但是,我将模型转换回JavaScript对象,以便我可以保存对服务器的任何更改:

I bind various UI elements to these fields, which works great. However, I convert the model back to a JavaScript object so I can save any changes to the server:

var goingToServer = ko.toJS(model);

goingToServer 将包含属性A,B和C.但是,假设属性C是一大块不会改变的数据。我想避免将其发送回服务器。

goingToServer will include properties A, B and C. However, let's say property C is a huge chunk of data that will never change. I'd like to avoid sending this back to the server.

有没有办法让 toJS()将模型转换回JavaScript对象时,包含一组预定义的字段?

Is there a way to make toJS() only include a predefined set of fields when converting a model back to a JavaScript object?

我一直在研究的一件事是 Knockout Mapping插件。它有一个名为 include 的设置,其记录如下:

One thing I've been investigating is the Knockout Mapping plugin. It has a setting called include which is documented as such:


将视图模型转换回JS时对象,默认情况下,
映射插件将只包含属于
原始视图模型的属性,除非它还包括
Knockout生成的_destroy属性,即使它不属于你的
原始对象。但是,您可以选择自定义此数组:

When converting your view model back to a JS object, by default the mapping plugin will only include properties that were part of your original view model, except it will also include the Knockout-generated _destroy property even if it was not part of your original object. However, you can choose to customize this array:

但是,看起来这个插件无法记录,因为<$ c即使我传入 include ['A','B'] 。我猜这个功能旨在包含其他字段,这些字段不在原始模型中。

However, it appears this plugin doesn't work as documented, as ko.mapping.toJS() will still include A, B and C, even if I pass in an include array of ['A', 'B']. I'm guessing this feature is intended to include additional fields that were not in the original model.

有没有办法排除某些属性将模型转换回JavaScript对象时,除了做一些hacky之外,比如生成对象并在发送到服务器之前手动删除我不想要的属性?

Is there a way to exclude certain properties when converting a model back to a JavaScript object, short of doing something hacky such as generating the object and manually removing the properties I don't want before sending to the server?

推荐答案

您是否尝试过 ignore 关键字?它与include的用法类似:

Have you tried the ignore keyword? It has a similar usage to the include:

var mapping = {
    'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}
var viewModel = ko.mapping.toJS(data, mapping);

您可以在执行服务器数据的原始映射时使用ignore,然后它不会当你把它转换回JS时,完全依赖你的对象。

You could just use ignore when you do the original mapping of the server data, then it won't be on your object at all when you convert it back to JS.

这篇关于如何从Knockoutjs中排除某些属性toJS()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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