我正在寻找在CRUD表单中使用的memento模式(GoF)的JavaScript实现。在它的基本级别上,撤销输入上的更改就足够了,但如果能和YUI或Ext这样的标准JS框架一起使用它来撤销和重做网格操作(新行、删除行等),那就更好了。
谢谢
发布于 2009-05-29 21:39:39
由于我没有看到任何代码示例,下面是一个EXT表单的撤销的快速实现:
var FormChangeHistory = function(){
this.commands = [];
this.index=-1;
}
FormChangeHistory.prototype.add = function(field, newValue, oldValue){
//remove after current
if (this.index > -1 ) {
this.commands = this.commands.slice(0,this.index+1)
} else {
this.commands = []
}
//add the new command
this.commands.push({
field:field,
before:oldValue,
after:newValue
})
++this.index
}
FormChangeHistory.prototype.undo = function(){
if (this.index == -1) return;
var c = this.commands[this.index];
c.field.setValue(c.before);
--this.index
}
FormChangeHistory.prototype.redo = function(){
if (this.index +1 == this.commands.length) return;
++this.index
var c = this.commands[this.index];
c.field.setValue(c.after);
}
Ext.onReady(function(){
new Ext.Viewport({
layout:"fit",
items:[{
xtype:"form",
id:"test_form",
frame:true,
changeHistory:new FormChangeHistory("test_form"),
defaults:{
listeners:{
change:function( field, newValue, oldValue){
var form = Ext.getCmp("test_form")
form.changeHistory.add(field, newValue, oldValue)
}
}
},
items:[{
fieldLabel:"type some stuff",
xtype:"textfield"
},{
fieldLabel:"then click in here",
xtype:"textfield"
}],
buttons:[{
text:"Undo",
handler:function(){
var form = Ext.getCmp("test_form")
form.changeHistory.undo();
}
},{
text:"Redo",
handler:function(){
var form = Ext.getCmp("test_form")
form.changeHistory.redo();
}
}]
}]
})
});在一个可编辑的网格中实现这一点有点棘手,但是您应该能够创建一个做同样事情的GridChangeHistory,然后从EditorGrid的AfterEdit侦听器中调用add()函数。
“之前”和“之后”属性可以是回调函数,它们允许您撤消/重做任何类型的命令,但在调用add()时需要做更多的工作。
发布于 2009-05-19 14:30:26
由于您正在尝试撤消/重做命令,因此我建议使用Command pattern。Here is a link to a tutorial;它是用C#编写的,但是对于OO程序员来说应该足够简单。
https://stackoverflow.com/questions/883033
复制相似问题