2009-05-19 14 views
5

Poszukuję implementacji JavaScript wzoru memento (GoF) do wykorzystania w formularzach CRUD. Na podstawowym poziomie wystarczy cofnąć zmiany na wejściach, ale byłoby wspaniale, gdyby używał go ze standardowymi strukturami JS, takimi jak YUI lub Ext, aby cofnąć & ponów akcje siatki (nowy wiersz, usuń wiersz itp.).Memento w JavaScript

Dzięki

Odpowiedz

6

Ponieważ nie widzę żadnych przykłady kodu, tutaj jest szybkie „n Brudne realizacja cofania do formularza 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(); 
       } 
      }] 
     }] 
    }) 
}); 

wykonawcza to dla edycji siatki jest trochę trudniejsze, ale zalecana być w stanie stworzyć GridChangeHistory, która robi to samo, a następnie wywołuje funkcję add() z programu nasłuchującego AfterEdit EditorGrid.

Właściwości "przed" i "po" mogą być funkcjami oddzwaniania, które umożliwiają cofanie/ponawianie dowolnego polecenia, ale wymagałoby to więcej pracy podczas wywoływania funkcji dodawania()