JavaScript命令模式的撤销操作

命令模式的撤销操作 撤销操作的实现一般是给命令对象增加一个名为unexecude或者undo的方法,在该方法里执行execute的反向操作,代码如下: var MoveCommand = function (receiver,pos) { this.receiver = receiver; this.pos = pos; this.oldPos = null; }; MoveCommand.prototype.execute = function () { this.receiver.start('left',this.pos,1000,'strongEaseOut'); this.oldPos = this.receiver.dom.getBoundingClienRect()[this.receiver.propertyName];//记录初始位置 }; MoverCommand.prototype.undo = function () { this.receiver.start('left',this.oldPos,1000,'strongEaseOut'); //撤销操作,回到之前运动的位置 }; var moveCommand; moveBtn.onclick = function() { var animate = new Animate(ball); moveCommand = new MoveCommand(animate,pos.value); moveCommand.execute(); }; cancelBtn.onclick = function () { moveCommand.undo(); } 撤销和重做 下面代码将讲述如何撤销一系列的命令 var Ryu = { attack :function () { console.log('攻击') }, defense:function() { console.log('防御') }, jump:function() { conosle.log('跳跃') }, crouch:function () { console.log('蹲下') } }; var makeCommand = function (receiver,state) { return function () { receiver[state](); } }; var commands = { "119":"jump", "115":"crouch", "97":"defense", "100":"attack" }; var commandStack = []; doccument.onkeypress = function (ev) { var keyCode = ev.keyCode, command = makCommand(Ryu,commands[keyCode]); if(command) { cammand(); commandStack.push(command);//保存刚才执行的动作 } }; //撤销的操作 document.getElementById('replay').onclick = function () { var command; while(command = commandStack.shift()) { command(); } }

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):