Created
January 23, 2014 15:01
-
-
Save yhbyun/8579939 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>Simple text editor with undo/redo features</title> | |
| <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> | |
| <script> | |
| function Originator() { | |
| this.prop = {}; | |
| } | |
| Originator.prototype.set = function($obj, $key) { | |
| this.prop = $obj; | |
| if ($key) this.save($key); | |
| }; | |
| Originator.prototype.save = function($key) { | |
| if (!this.prop) return; | |
| if (!this.stack) this.stack = []; | |
| this.stack[$key] = $.extend({}, this.prop); | |
| }; | |
| Originator.prototype.get = function($key) { | |
| return this.prop[$key]; | |
| }; | |
| Originator.prototype.restore = function($key) { | |
| var prop = this.stack && this.stack[$key]; | |
| if (!prop) return; | |
| this.prop = prop; | |
| }; | |
| Originator.prototype.delete = function($key) { | |
| if (this.stack && this.stack[$key]) delete this.stack[$key]; | |
| } | |
| function Text($textarea) { | |
| this.constructor.call(this); | |
| this.cursor = this.max = 0; | |
| this.text = $textarea; | |
| } | |
| Text.prototype = new Originator; | |
| Text.prototype.run = function() { | |
| var self = this; | |
| this.text.value = this.prop.str; | |
| setTimeout(function() { | |
| self.text.selectionEnd = self.text.selectionStart = self.prop.pos; | |
| },1); | |
| }; | |
| Text.prototype.store = function() { | |
| this.max = ++this.cursor; | |
| this.set({pos:this.text.selectionStart, str:this.text.value}, this.cursor); | |
| }; | |
| Text.prototype.undo = function() { | |
| this.restore(--this.cursor); | |
| this.run(); | |
| }; | |
| Text.prototype.redo = function() { | |
| if (this.cursor == this.max) return; | |
| this.restore(++this.cursor); | |
| this.run(); | |
| }; | |
| </script> | |
| <style> | |
| #txt {width:400px; height:200px} | |
| </style> | |
| </head> | |
| <body> | |
| <textarea id="txt"></textarea> | |
| <button id="undo">undo</button> | |
| <button id="redo">redo</button> | |
| <script> | |
| var txt = new Text($('#txt')[0]); // receiver | |
| var count = 0; | |
| $('#txt').on('keydown', function($e) { | |
| if($e.keyCode == 13 || $e.keyCode == 32) { //enter, space | |
| if (count > 2) { | |
| count = 0; | |
| txt.store(); | |
| } else count++; | |
| } | |
| }); | |
| $('#undo').on('click', function($e){txt.undo(); }); | |
| $('#redo').on('click', function($e){txt.redo(); }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment