如何取消/恢复对可观察模型的更改(或使用未经修改的副本替换数组中的模型) [英] How to cancel/revert changes to an observable model (or replace model in array with untouched copy)

查看:76
本文介绍了如何取消/恢复对可观察模型的更改(或使用未经修改的副本替换数组中的模型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有observableArray对象且带有可观察变量的viewModel。

I have a viewModel with an observableArray of objects with observable variables.

我的模板显示带有编辑按钮的数据,该按钮隐藏显示元素并显示输入元素绑定的值。您可以开始编辑数据,然后您可以选择取消。我希望这个取消恢复到对象的未更改版本。

My template shows the data with an edit button that hides the display elements and shows input elements with the values bound. You can start editing the data and then you have the option to cancel. I would like this cancel to revert to the unchanged version of the object.

我尝试通过这样的方式克隆对象:

I have tried clone the object by doing something like this:

viewModel.tempContact = jQuery.extend({}, contact);

viewModel.tempContact = jQuery.extend(true, {}, contact);

但是一旦联系人,viewModel.tempContact就会被修改。

but viewModel.tempContact gets modified as soon as contact does.

KnockoutJS中是否有任何东西可以处理这种情况,或者我最好只是创建一个具有完全相同细节的新联系人,并在取消时用新联系人替换修改后的联系人?

Is there anything built into KnockoutJS to handle this kind of situation or am I best off to just create a new contact with exactly the same details and replace the modified contact with the new contact on cancel?

非常感谢任何建议。谢谢!

Any advice is greatly appreciated. Thanks!

推荐答案

有几种方法可以处理这样的事情。您可以使用与当前值相同的值构造一个新对象,并在取消时将其抛弃。您可以添加其他可观察对象以绑定到编辑字段并将其保留在接受上或查看此 post ,关于将此功能封装到可重用类型中的想法(这是我首选的方法)。

There are a few ways to handle something like this. You can construct a new object with the same values as your current one and throw it away on a cancel. You could add additional observables to bind to the edit fields and persist them on the accept or take a look at this post for an idea on encapsulating this functionality into a reusable type (this is my preferred method).

这篇关于如何取消/恢复对可观察模型的更改(或使用未经修改的副本替换数组中的模型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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