basic implementation of the Command Design Pattern in JavaScript

A basic implementation of the Command Design Pattern in JavaScript:

This design pattern is especially useful if you are drawing complex objects on a HTML5 Canvas, and you want to first build the objects, do some work, and then later draw the objects.

 /** @constructor  
 * An operation on an object. Use this to cache commands that will be performed later (Command Design Pattern).  
 */  
 var Command = function (me, fun, args) {  
   this.me = me;  
   this.fun = fun;  
   this.args = args;  
 };  
 /** Do the command.  
 */  
 Command.prototype.Do = function () {  
   this.fun.apply(this.me, this.args);  
 };  

Example usage:

 //scratch code to show how to use Command:  
 var obj = {  
  Action: function(one, two, three) {  
   //do something  
  }  
 };  
 var commands = [];  
 commands.push(new Command(obj, obj.Action, [1,2,3]); //repeat this line as needed  
 //do some other work  
 //...  
 //now decide whether to go ahead and perform the cached commands:  
 var okToGoAhead = true;  
 if(okToGoAhead) {  
  for(var i=0; i< commands.length; i++) {  
   commands[i].Do();  
  }  
 }  

Comments