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

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

问题描述

我有一个带有可观察变量的 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!

推荐答案

有几种方法可以处理此类问题.您可以构造一个与当前对象具有相同值的新对象,然后在取消时将其丢弃.您可以添加额外的 observables 以绑定到编辑字段并将它们保留在接受或查看此 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天全站免登陆