如何在javascript中处理undo / redo事件?

时间:2013-03-20 05:45:28

标签: javascript jquery

我正在尝试使用Javascript& amp;来检测表单输入的值是否发生变化JQuery的。不幸的是,我发现JQuery的$(elem).change()不足,因为它只会在elem失去焦点时触发更改事件。当表单输入值发生变化时,我必须立即知道。为此,我将与输入值可能更改相关的事件缩小到 keyup 粘贴 cut 撤消重做。但是,javascript和JQuery似乎都无法处理撤消或重做。

var onChange = function ()
{
    alert('Checking for changes...');
};

$(this).off('keyup').on('keyup', onChange);
$(this).off('paste').on('paste', onChange);
$(this).off('cut').on('cut', onChange);

$(this).off('undo').on('undo', onChange);  // undo ?
$(this).off('redo').on('redo', onChange);  // redo ?

我在Javascript / JQuery中搜索了undo / redo事件,但没有找到任何有用的信息。有人可以帮忙解决如何处理撤消/重做事件吗?

6 个答案:

答案 0 :(得分:4)

javascript中没有撤消或重做事件。如果你想要这样的功能,你要么必须自己在javascript中编写它,要么找一个提供这种功能的库。

如果您试图捕获所有可能的方式来更改输入控件,以便您可以立即看到这样的更改,那么请查看以下示例代码:http://jsfiddle.net/jfriend00/6qyS6/,它实现了一个更改回调输入控制。此代码不是直接设计用于下拉列表,但由于它是输入控件的一种形式,因此您可以调整此代码以创建自己的下拉变换事件。

好吧,StackOverflow以他们的无限智慧禁止我只发布对jsFiddle的引用,所以我必须在这里粘贴所有代码(出于某种原因,jsFiddles被挑出来而不是其他web引用)。我不是将其表示为一个精确的解决方案,但作为模板,您可以使用它来检测用户对输入控件的更改:

(function($) {

    var isIE = false;
    // conditional compilation which tells us if this is IE
    /*@cc_on
    isIE = true;
    @*/

    // Events to monitor if 'input' event is not supported
    // The boolean value is whether we have to 
    // re-check after the event with a setTimeout()
    var events = [
        "keyup", false,
        "blur", false,
        "focus", false,
        "drop", true,
        "change", false,
        "input", false,
        "textInput", false,
        "paste", true,
        "cut", true,
        "copy", true,
        "contextmenu", true
    ];
    // Test if the input event is supported
    // It's too buggy in IE so we never rely on it in IE
    if (!isIE) {
        var el = document.createElement("input");
        var gotInput = ("oninput" in el);
        if  (!gotInput) {
            el.setAttribute("oninput", 'return;');
            gotInput = typeof el["oninput"] == 'function';
        }
        el = null;
        // if 'input' event is supported, then use a smaller
        // set of events
        if (gotInput) {
            events = [
                "input", false,
                "textInput", false
            ];
        }
    }

    $.fn.userChange = function(fn, data) {
        function checkNotify(e, delay) {
            // debugging code
            if ($("#logAll").prop("checked")) {
                log('checkNotify - ' + e.type);
            }

            var self = this;
            var this$ = $(this);

            if (this.value !== this$.data("priorValue")) {
                this$.data("priorValue", this.value);
                fn.call(this, e, data);
            } else if (delay) {
                // The actual data change happens after some events
                // so we queue a check for after.
                // We need a copy of e for setTimeout() because the real e
                // may be overwritten before the setTimeout() fires
                var eCopy = $.extend({}, e);
                setTimeout(function() {checkNotify.call(self, eCopy, false)}, 1);
            }
        }

        // hook up event handlers for each item in this jQuery object
        // and remember initial value
        this.each(function() {
            var this$ = $(this).data("priorValue", this.value);
            for (var i = 0; i < events.length; i+=2) {
                (function(i) {
                    this$.on(events[i], function(e) {
                        checkNotify.call(this, e, events[i+1]);
                    });
                })(i);
            }
        });
    }
})(jQuery);    

function log(x) {
    jQuery("#log").append("<div>" + x + "</div>");
}

// hook up our test engine    
$("#clear").click(function() {
    $("#log").html("");
});


$("#container input").userChange(function(e) {
    log("change - " + e.type + " (" + this.value + ")");
});

答案 1 :(得分:4)

您可以使用MutationObserver监控所有更改。这不会为每个keydown和keyup提供事件,但它可以整合多个更改并将其作为单个事件发送给您。

  var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
  var observer = new MutationObserver(function(mutations) {  
    mutations.forEach(function(mutation) {
        // mutation.target will give you element which has been modified.
        // mutation.addedNodes and mutation.removedNodes will give you operations that were performed on the node
        // happy coding :)
      });
  });
  observer.observe(elementsToMonitor, {
    attributes: true, 
    childList: true, 
    characterData: true 
   });

有关MutationObserver的更多信息 https://developer.mozilla.org/en/docs/Web/API/MutationObserver

答案 2 :(得分:2)

John Resig(JQuery的创建者)的热键可以提供帮助

https://github.com/jeresig/jquery.hotkeys

来自自述文件

  

如果你想使用多个修饰符(例如alt + ctrl + z),你应该按字母顺序定义它们,例如: Alt + Ctrl +移

答案 3 :(得分:0)

<input type="text"/>
<script>
var newInput = "";
var oldInput = [$('input').val()];
$('input').on('input',function(){
    newInput = $(this).val();
    redo = false;
    $(oldInput).each(function(i){if(newInput==oldInput[i]){redo = true; return false});
    if(redo){
        console.log('do code for an undo or redo');
    }
oldInput.push(newInput);
console.log([oldInput,newInput]);
});
</script>

基本概念是存储先前的输入值并检查新输入值是否等于前一个输入值之一。它不完美(例如退格触发它)和效率低一点(见下一段),但你应该能够得到你想要的结果。

不是保留所有先前的输入,而是可以查看撤消代码以查看它实际保留的内容(我认为它只会使大多数输入丢失,因为它们在彼此的时间范围内)。

答案 4 :(得分:0)

曾经有一段时间我在我正在开展的项目中需要这样的东西。对于我来说,标记的解决方案似乎并不优雅。我在这里用了几个回答的组合来做这件事。

function UndoListener(options){
    if(!options.el instanceof HTMLElement) return;
    this.el = options.el;
    this.callback = options.callback || function(){};
    this.expectedChange = false;
    this.init();
}

UndoListener.prototype = {
    constructor: UndoListener,
    addListeners: function(){
        this.el.addEventListener('keydown', (e) => this.expectedChange = this.eventChecker(e));
        this.el.addEventListener('cut', (e) => this.expectedChange = true);
        this.el.addEventListener('paste', (e) => this.expectedChange = true);
    },
    addObserver: function(){
        this.observer = new MutationObserver((mt) => {
            if(!this.expectedChange){
                this.expectedChange = true;
                this.observer.disconnect();
                this.callback.call(this.el, {
                    original: [...mt].shift().oldValue,
                    current: this.el.innerText
                });
                this.addObserver();
            }
            this.expectedChange = false;
        });

        this.observer.observe(this.el, {
            characterData: true,
            subtree: true,
            characterDataOldValue: true
        });
    },
    eventChecker: function(event) {
        return !(~['z','y'].indexOf(event.key) && (event.ctrlKey || event.metaKey));
    },
    init: function(){
        this.addListeners();
        this.addObserver();
    }
}

这使用MutationObserver来“捕获”撤消事件。这样做是因为MutationObserver在事件触发后触发。我们检查事件是否是预期事件,如keydown或cut,并允许在没有回调触发的情况下进行更改。如果事件是意外的,我们假设已发生撤消。这无法区分撤销和重做;回调将触发。用法:

var catcher = new UndoListener({
    el: document.querySelector('.container'),
    callback: function(val){
        console.log('callback fired', val);
    }
});

我有working in action on codepen

答案 5 :(得分:0)

I created a state undo/redo snapshot manager class, which would be great for tracking the change history on an entire HTML element with child inputs. If you want to take snapshots on a more granular level, you can bind on keypress events instead of the change events I used in my example.

  <div id="buttons">
     <button type="button" id="undo_btn">Undo</button>
     <button type="button" id="redo_btn">Redo</button>
  </div>
  <br/><br/>
  <div id="content">
     <label>
        Input1:
        <input type="text" value="" />
     </label>
     <br/><br/>
     <label>
        Input2:
        <input type="text" value="" />
     </label>
     <br/><br/>
     <label>
        Input3:
        <input type="text" value="" />
     </label>
     <br/><br/>
     <label>
        Input4:
        <input type="text" value="" />
     </label>
     <br/><br/>
  </div>

  <script type="text/javascript">
  var StateUndoRedo = function() {
     var init = function(opts) {
        var self = this;
        self.opts = opts;
        if(typeof(self.opts['undo_disabled']) == 'undefined') {
           self.opts['undo_disabled'] = function() {};
        }
        if(typeof(self.opts['undo_enabled']) == 'undefined') {
           self.opts['undo_enabled'] = function() {};
        }
        if(typeof(self.opts['redo_disabled']) == 'undefined') {
           self.opts['redo_disabled'] = function() {};
        }
        if(typeof(self.opts['redo_enabled']) == 'undefined') {
           self.opts['redo_enabled'] = function() {};
        }
        if(typeof(self.opts['restore']) == 'undefined') {
           self.opts['restore'] = function() {};
        }
        self.opts['undo_disabled']();
        self.opts['redo_disabled']();
     }

     var add = function(state) {
        var self = this;
        if(typeof(self.states) == 'undefined') {
           self.states = [];
        }
        if(typeof(self.state_index) == 'undefined') {
           self.state_index = -1;
        }
        self.state_index++;
        self.states[self.state_index] = state;
        self.states.length = self.state_index + 1;
        if(self.state_index > 0) {
           self.opts['undo_enabled']();
        }
        self.opts['redo_disabled']();
     }

     var undo = function() {
        var self = this;
        if(self.state_index > 0) {
           self.state_index--;
           if(self.state_index == 0) {
              self.opts['undo_disabled']();
           } else {
              self.opts['undo_enabled']();
           }
           self.opts['redo_enabled']();

           self.opts['restore'](self.states[self.state_index]);
       }
     }

     var redo = function() {
        var self = this;
        if(self.state_index < self.states.length) {
           self.state_index++;
           if(self.state_index == self.states.length - 1) {
              self.opts['redo_disabled']();
           } else {
              self.opts['redo_enabled']();
           }
           self.opts['undo_enabled']();

           self.opts['restore'](self.states[self.state_index]);
       }
     }

     var restore = function() {
        var self = this;
        self.opts['restore'](self.states[self.state_index]);
     }

     var clear = function() {
        var self = this;
        self.state_index = 0;
        //self.states = [];
     }

     return {
        init: init,
        add: add,
        undo: undo,
        redo: redo,
        restore: restore,
        clear: clear
     };
  };

  //initialize object
  var o = new StateUndoRedo();
  o.init({
     'undo_disabled': function() {
        //make the undo button hidden
        document.getElementById("undo_btn").disabled = true;
     },
     'undo_enabled': function() {
        //make the undo button visible
        document.getElementById("undo_btn").disabled = false;
     },
     'redo_disabled': function() {
        //make the redo button hidden
        document.getElementById("redo_btn").disabled = true;
     },
     'redo_enabled': function() {
        //make the redo button visible
        document.getElementById("redo_btn").disabled = false;
     },
     'restore': function(state) {
        //replace the current content with the restored state content
        document.getElementById("content").innerHTML = state;
     }
  });

  //initialize first state
  o.add(document.getElementById("content").innerHTML);
  o.restore();
  o.clear();

  //bind click events for undo/redo buttons
  document.getElementById("undo_btn").addEventListener("click", function() {
     o.undo();
  });
  document.getElementById("redo_btn").addEventListener("click", function() {
     o.redo();
  });

  //bind change events for content element
  document.getElementById('content').addEventListener("change", function(event) {
     // the following is required since vanilla JS innerHTML 
     // does not capture user-changed values of inputs
     // so we set the attributes explicitly (use jQuery to avoid this)
     var elems = document.querySelectorAll("#content input");
     for(var i = 0; i < elems.length; i++) {
        elems[i].setAttribute("value", elems[i].value);
     }

     //take a snapshot of the current state of the content element
     o.add(document.getElementById("content").innerHTML);
  });
  </script>

See this JSFiddle: https://jsfiddle.net/up73q4t0/56/