Offline
Online
Viewers

JavaScript Command Pattern

For this example of a Command pattern, we will create a simple “Interpreter” object and a basic “Command” object and demonstrate their respective use. Let’s first start with the “Interpreter”:
[codesyntax lang=”javascript”]

var Interpreter = { 
    execute: function(command){ 
        //split on the space 
        var commandArray = command.split(" "); 

        try{ 
            //use first entry as command name 
            var commandName = commandArray[0]; 

            //retrieve a reference to the real command object 
            var commandObject = eval(commandName); 

            //execute the command 
            commandObject.execute(command); 
        } catch(ex){ 
            //handle exception 
        }//end tc 
    } 
};

[/codesyntax]

Ok, so what have we done here? We’ve created a basic pseudo structure with a single method called “execute”. The reason for the pseudo structure instead of a JavaScript class, is simply choice for this example. In this example we will only need to use a single “Interpreter” object, so this just seemed to make sense. Within the “Interpreter” object, the “execute” function takes a single parameter called “command”. The command parameter might be something like the following “MyCommand ‘Hello World'”, in which the command to execute would be “MyCommand” and the parameter passed to the “MyCommand” object would be ‘Hello World’. Within the “execute” method, we do the following: first we break the command string apart to located the command name, next we evaluate the command name to return a reference to a real object with the same name. Next, we call the referenced command object’s “execute” method and pass in the original command string. Now let’s have a look at a sample command object:
[codesyntax lang=”javascript”]

var MyCommand = { 
    execute: function(command){ 
        //do something 
        var args = command.replace("MyCommand ", ""); 
        alert(args); 
    } 
};

[/codesyntax]

Wow, that’s simple. The “MyCommand” object is a simple pseudo structure with a single method called “execute”. The “execute” method expects to receive a command string and in this case, we just remove the command name from the string and alert the arguments passed to make sure it works. Next we need to try it out:
[codesyntax lang=”javascript”]

Interpreter.execute("MyCommand 'Hello World'");

[/codesyntax]

There we go. If all went well we should have seen the alert with “Hello World” in it. That’s all there is to it, try it yourself.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Affiliates