2009-05-19 13 views
5

Sto cercando un'implementazione JavaScript del pattern memento (GoF) da utilizzare nei moduli CRUD. Nel suo livello base sarà sufficiente annullare le modifiche sugli input, ma sarebbe bello utilizzarlo con framework JS standard come YUI o Ext, per annullare le azioni di griglia & redo (nuova riga, cancella riga ecc.).Memento in Javascript

Grazie

risposta

6

Dal momento che non riesco a visualizzare alcun esempi di codice, ecco un breve 'n sporco implementazione di annullamento per un modulo 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(); 
       } 
      }] 
     }] 
    }) 
}); 

implementazione di questo per una griglia modificabile è un po' più complicato, ma si dovrebbe essere in grado di creare una GridChangeHistory che faccia la stessa cosa e quindi chiamare la funzione add() dal listener AfterEdit di EditorGrid.

La "prima" e "dopo" le proprietà potrebbero essere le funzioni di callback che permettono di Annulla/Ripristina qualsiasi tipo di comando, ma che richiederebbe più lavoro al momento della chiamata add()