首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript中的Memento

Javascript中的Memento
EN

Stack Overflow用户
提问于 2009-05-19 14:13:53
回答 2查看 4.1K关注 0票数 5

我正在寻找在CRUD表单中使用的memento模式(GoF)的JavaScript实现。在它的基本级别上,撤销输入上的更改就足够了,但如果能和YUI或Ext这样的标准JS框架一起使用它来撤销和重做网格操作(新行、删除行等),那就更好了。

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-05-29 21:39:39

由于我没有看到任何代码示例,下面是一个EXT表单的撤销的快速实现:

代码语言:javascript
复制
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()时需要做更多的工作。

票数 6
EN

Stack Overflow用户

发布于 2009-05-19 14:30:26

由于您正在尝试撤消/重做命令,因此我建议使用Command patternHere is a link to a tutorial;它是用C#编写的,但是对于OO程序员来说应该足够简单。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/883033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档