2 * undone.js 0.0.1 - https://github.com/yckart/undone.js
3 * The undo/redo manager for well formed javascript applications.
5 * Inspired by: http://blog.asgaard.co.uk/2012/11/21/undo-redo-in-javascript
7 * Copyright (c) 2012 Yannick Albert (http://yckart.com)
8 * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
16 var Undone = function(options) {
18 // define the defaults
23 // extend the defaults
24 for(var i in options) this.options[i] = options[i];
33 * Executes an action and adds it to the undo stack.
34 * @param {Function} action - Action function.
35 * @param {Function} reverse - Reverse function.
36 * @param {Object} ctx - The 'this' argument for the action/reverse functions.
38 Undone.prototype.register = function(action, reverse, ctx) {
39 if(this.history.undo.length >= this.options.buffer) this.history.undo.unshift();
40 this.history.undo.push( {action: action, reverse: reverse, ctx: ctx} );
42 this.history.redo.length = 0;
43 this.change("register", this.history.undo.length, this.history.redo.length);
46 Undone.prototype.undo = function(n) {
47 var len = this.history.undo.length;
51 if(len < this.options.buffer) {
53 var c = this.history.undo.pop();
56 c.reverse.call(c.ctx);
57 this.history.redo.push(c);
59 if( len !== this.history.undo.length ) this.change("undo", this.history.undo.length, this.history.redo.length);
63 Undone.prototype.redo = function(n) {
65 var len = this.history.redo.length;
69 if(len < this.options.buffer) {
71 var c = this.history.redo.pop();
74 this.history.undo.push(c);
76 if( len !== this.history.redo.length ) this.change("redo", this.history.undo.length, this.history.redo.length);
80 Undone.prototype.onChange = function(){};
81 Undone.prototype.change = function(event, undoLen, redoLen){
82 if (this.onChange) this.onChange(event, undoLen, redoLen);
83 if(window.jQuery) $(window).trigger("undone:change", [event, undoLen, redoLen]);
86 Undone.prototype.clear = function(){
91 this.change("clear", 0, 0);
94 window.Undone = Undone;