If use databinding in a dialog, how to restore data when user cancelled the editing?

只谈情不闲聊 提交于 2019-12-11 09:13:07

问题


If I get a bean and a dialog, and they are coupled with bidirectional data-binding, what is the best way to roll back to the original bean when user canceled the editing.

EDIT 1

If user opened up the dialog in edit mode, he then did some modification and pressed "OK", then this dialog closed and the underlying bean got updated. When I said "canceled the editing", I mean the user opened up the dialog and did some modification but pressed "cancel" button. In this case, the underlying bean should keep untouched, but due to data-binding, it become dirty, I want the original bean back.

I can just clone a bean when the dialog opens, if user presses "OK" the cloned bean will be copied back to original bean; if user presses "cancel" the cloned bean will be abandoned. I don't know if this is a good approach.


回答1:


I have always used the clone approach quite successfully. The clone approach comes in two varieties: bind to clone and bind to original.

Bind to clone will make it so any other binding to the same field on the screen will not update while your dialog box is up. When OK is pressed you copy the clone to the original object, on cancel you simply throw the clone away.

Bind to original allows screen updates to others components bound to the same field. When OK is pressed you throw the clone away. When cancel is pressed you copy the clone to the original.

I favor the bind to clone approach since I think it is confusing to see other on screen components updating while a dialog box is up. I think it creates confusion as to whether cancel will rollback changes that are appearing outside the dialog box.

The alternative is to use a flushable binding strategy where a binding can be set up in such a way that it will not update the object until some kind of flush() method has been called. If your databinding framework does not support this then it can be a lot of work to tack this on later.




回答2:


What do you mean by "canceled the editing?" Without some example code, it's hard to help. The most generic solution is to store the previous value as a variable somewhere.

Perhaps implement a PropertyChangeListener? You can grab the old value via PropertyChangeEvent.getOldValue()? Maybe a VetoableChangeListener may work for you too.



来源:https://stackoverflow.com/questions/3666311/if-use-databinding-in-a-dialog-how-to-restore-data-when-user-cancelled-the-edit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!