Tag Archives: javascript

Drawing on Textures in ThreeJS

If you’re an avid user of ThreeJS you have more than likely at some point run into the situation where you need to either create a texture from scratch for the point of coloring it, or have had the need to update/draw on a texture for one reason or another.  The following will walk you through what is needed to accomplish this.

First, start by creating an in memory canvas object that we will use to draw on.  This will eventually be transformed into a texture object.

//create in memory canvas
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext("2d");

 

For this example, I’m creating a simple 100×100 pixel image and retrieving the 2d context which we will next use for performing that actual modification of the image.

//paint the image red
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 100, 100);

 

Here we’re setting the fill color to red and painting the entire image.  Next, let’s convert our in memory canvas object into an image.

//create image from canvas
var image = new Image();
image.src = canvas.toDataURL();

 

Finally, let’s take our new image and create a texture object which can be applied to a material.

//create new texture
var texture = new THREE.Texture(image);
texture.anisotropy = 4;
texture.needsUpdate = true;
 
//apply texture to a material, go forth and be merry

 

That’s really all there is to it, you can make the context draw lines, rects, etc. onto the in memory canvas until your heart’s content.  For convenience, the following is the entire code example wrapped up into one.

//create in memory canvas
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var context = canvas.getContext("2d");
 
//paint the image red
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 100, 100);
 
//create image from canvas
var image = new Image();
image.src = canvas.toDataURL();
 
//create new texture
var texture = new THREE.Texture(image);
texture.anisotropy = 4;
texture.needsUpdate = true;
 
//apply texture to a material, go forth and be merry

New Rubik’s Cube jQuery Plugin

I consider myself an avid speed cuber. Not world class, but fast enough and not too obsessed with it. That being said all the sites I’ve seen in the past with references to algorithms all seem to use really clunky client side Java or Flash plugins to handle the demonstration of moves.  I wanted to create a simple to implement jQuery plugin that utilizes the browser’s built in features to do the same thing.  The result is my jquery.cube.js plugin. As seen below.

The plugin code is available here: https://github.com/godlikemouse/jquery.cube.js

 

See the Pen jQuery and CSS Implemented Rubik’s Cube by Jason Graves (@godlikemouse) on CodePen.

This plugin utilizes standard cube notation, both modern and old to execute moves. For example, the moves executed above are utilizing the following notation:

x (R’ U R’) D2 (R U’ R’) D2 (R U R’) D2 (R U’ R’) D2 (R U R’) D2 (R U’ R’) D2 R2 x’

This algorithm is being passed to the cube plugin by way of the execute() method.

This plugin currently supports a number of configuration options that can be passed at instantiation time including, cube face colors, animation delay time with more to come shortly.

For more information on this plugin or to view the source please visit: https://github.com/godlikemouse/jquery.cube.js

D3 and jQuery Interoperability

D3 and jQuery utilize distinctly different approaches to node manipulation and internal array storage. However, there are mechanisms available for converting between D3 and jQuery, and vice versa.

D3 and jQuery Internals

Let’s assume the following HTML structure:

<div class="test-node">Test One</div>
<div class="test-node">Test Two</div>
<div class="test-node">Test Three</div>
<div class="test-node">Test Four</div>

Now let’s retrieve the “test-node” elements with jQuery:

var testNodes = $(".test-node");
console.log(testNodes);

Console Log

As can be seen above, jQuery stores the selected elements in a first level array, making elements accessible by testNodes[0…3] as expected.  Now let’s examine the D3 equivalent:

var testNodes = d3.selectAll(".test-node");
console.log(testNodes);

Console Log

When using D3, the selected elements get stored in a second level array making the elements accessible by testNode[0][0…n].

Converting from jQuery to D3

var $testNodes = $(".test-node");  //jquery
var testNodes = d3.selectAll( $testNodes.toArray() ); //d3
console.log(testNodes);

Console Log

The above first retrieves the nodes using standard jQuery selector syntax.  Next the “toArray()” method is called returning the native array of selected elements.  Finally the “d3.selectAll()” method is invoked using the native array as the argument.  This forces the native element array into the second level array of D3.

Converting from D3 to jQuery

var testNodes = d3.selectAll(".test-node");
var $testNodes = $(testNodes[0]);
console.log($testNodes);

Console Log

The above first retrieves the nodes using D3 selector syntax.  Next the first level D3 array is used as the argument passed into the jQuery selector.

Class Addition/Removal

Adding and removing a class in jQuery is pretty straightforward:

$(".test-node").addClass("selected"); //add class "selected"
$(".test-node").removeClass("selected"); //remove class "selected"

The same performed in D3 is performed using the following:

d3.selectAll(".test-node").classed("selected", true); //add class "selected"
d3.selectAll(".test-node").classed("selected", false); //remove class "selected"

Data/Datum

D3 has a very elegant data system whereby information can be bound to elements by use of the “datum()” method.

D3 Datum

Let’s examine the following:

var nodes = d3.selectAll(".test-node")
    .datum({key: "hello", value: "world"})
    .append("span");
 
console.log(nodes);

Console Log

The above example selects all of the “.test-node” div classed elements utilizing D3, initializes a data structure/object and passes this structure/object to the “span” elements which get appended to all the matching “.test-node” div classed elements.  This “datum()” method passes the data structure/object to the “span” elements using a property called “__data__”.  As displayed above, the __data__ property has the structure of:

__data__: {
    key: "hello",
    value: "world"
}

The “__data__” property can be accessed directly using second level array syntax (ie. d3.selectAll(“span”)[0][0…n].__data__) or it can be utilized as a default argument passed into nearly all D3 selector instance methods.  Let’s examine an instance method where this takes place:

var nodes = d3.selectAll(".test-node")
    .datum({key: "hello", value: "world"})
    .append("span")
    .text(function(d){
        return d.key + " " + d.value;
    });

In the above example, the only difference from the previous example is the instance method “text()”, whereby the argument passed is a function.  This function defines an argument “d” which D3 passes to these type of instance methods automatically.  The “d” argument being the actual data/datum used to initialize the “span” elements.  The body of the text function returns the string “hello world” using the data/datum, thusly setting the text of the “span” elements to “hello world”.

jQuery Data

jQuery has a simple mechanism for adding arbitrary data to elements by use of the “data()” method.  Let’s examine the following:

var nodes = $(".test-node")
    .append("span")
    .data("datum", {key: "hello", value: "world"});
 
console.log(nodes);
console.log($.cache);

Console Log

In the above example, the “.test-node” elements are retrieved, “span” elements are appended and the datum {key: “hello”, value: “world”} is added to the data.  The console output reveals that the datum is stored in the $.cache in jQuery.

Exchanging D3 Datum with jQuery

Now that we’ve seen how both D3 and jQuery store data/datum, let’s exchange D3 datum with jQuery:

//D3
var nodes = d3.selectAll(".test-node")
    .datum({key: "hello", value: "world"})
    .append("span");
 
console.log(nodes);
 
//jQuery
var $nodes = $(nodes[0]);
$nodes.each(function(){
    $(this).data("datum", $(this).prop("__data__"));
});
 
console.log($nodes);
console.log($.cache);

Console LogIn this example, we first select the “.test-node” classed elements using D3, append “span” elements using the datum/data specified.  Next, we create a jQuery selector using the first level array of the D3 selector.  Using the jQuery selector, the nodes are iterated over in “each” and the “data()” of the jQuery element is set to the “__data__” property of the D3 element.

Exchanging jQuery Data With D3

Now, let’s exchange jQuery data with D3 using a similar technique to the previous example:

//jQuery
var $nodes = $(".test-node")
    .append("span")
    .data("datum", {key: "hello", value: "world"});
 
console.log($nodes);
console.log($.cache);
 
//D3
var nodes = d3.selectAll($nodes.toArray())
    .datum({})
    .each(function(d){
        this.__data__ = $(this).data("datum");
    });
 
console.log(nodes);

Console LogIn the above example, the “.test-node” elements are selected using jQuery, the span child elements are appended and the “data()” method is used to store the “datum” {key: “hello”, value: “world”}.  Next, the D3 selector is populated using the “toArray()” method of the jQuery selector, the “datum()” method is used to initialize an empty data object and finally the nodes are iterated over and the __data__ property is populated with the jQuery data “datum”.

Conclusion

Both frameworks are very powerful and can live together in peace.  Information can be exchanged freely between the the two frameworks utilizing these or similar techniques.

Create jQuery Plugins: The Easy Way

If you’re a solid user of jQuery or just a tinkerer you may have thought to yourself “I have a great idea for a jQuery plugin”.  Your next steps of course would probably be to look at the jQuery documentation and eventually to have a look at someone else’s jQuery plugin source code.  In doing so you may have said to yourself or aloud “From what depths of perdition hath this code been spawned!”  I’ve seen quite a few jQuery plugin source files and they are, how do I put this delicately…written like crap a lot of the time.  Truth is, there’s an easy and elegant way to build jQuery plugins.

Let’s start with a simple example.  Let’s say you want to build a plugin that changes the color of all the nodes referenced by a selector.  In other words $(“.make-me-red”).red(); a very simple approach with the plugin actually called “red”.  Here’s the code:

Some simple HTML

<div class="make-me-red">One</div>
<div class="make-me-red">Two</div>
<div class="make-me-red">Three</div>

 

The jQuery plugin code

$.fn.red = function(){
    $(this).css("color", "red");
}

 

Invoke the plugin

$(function(){
    $(".make-me-red").red();
});

 

Yes, yes, magical…I know.  That’s all there really is to it, let’s walk through the plugin code.  The “$” or “jQuery” reference has an object called “fn”, functions bound to this object are accessible from the returned selector array.  The “this” variable referenced in the function body contains all the elements matching the selector at the time of the call.  The “css()” method call applies the style attribute with color=”red” to all matching selector elements.  Easy peasy, now let’s try something a bit more useful.

Let’s create a jQuery plugin that makes use of options being passed in and performs something semi-useful, not too useful, just semi-useful.  Check it out:

Some simple HTML

<div class="make-me-move">Hi There!</div>

 

The jQuery Plugin Code

$.fn.jiggle = function(options){
 
    //setup default options
    var defaultOptions = {
        duration: 500,
        amount: 10
    };
 
    //apply passed in options to default options
    options = $.extend(defaultOptions, options);
 
    //divide the time into fourths
    var d = options.duration/4;
 
    //animate the element
    $(this)
        .css("position", "relative")
        .animate({left: -options.amount}, d)
        .animate({left: -options.amount}, d)
        .animate({left: -options.amount}, d)
        .animate({left: -options.amount}, d)
        .animate({left: 0}, d);
}

 

Invoke the plugin

$(function(){
    $(".make-me-move").jiggle();
});

 

Now that was a bit more complex, let’s walk through it.  This plugin is called “jiggle”, wonder why.  The first change here is the options variable being passed in.  This variable allows the plugin to be configurable from the calling code.  In this instance we have exposed the duration (in milliseconds) and the amount (movement).  The first thing we do is set default values to handle the case that the calling code does not pass anything, this is the purpose of the “defaultOptions”.  Next we make a call to $.extend to override any default values passed into the plugin from the calling code by way of “options”.  We then set options to the merged result of “defaultOptions” and “options” (where “options” overrides “defaultOptions”), that way we have a single reference to all the values we will use.  Finally, we animate the elements by changing the css position and making subsequent calls to the animate method.  Now let’s invoke the same call again with custom values passed in by way of “options”

$(function(){
    $(".make-me-move").jiggle({
        duration: 1000
    });
});

 

Implementing options the way we have in our plugin code allows us to optionally (pun intended) pass some, all or none of the values into the calling code.  With this example we have set the duration to 1 second (1000 milliseconds).  Simple.

Hopefully this quick start will help propel you into the halls of fame in the jQuery plugin community, and if not, that’s cool too 🙂  Thanks for reading.

Understanding JavaScript Promises In jQuery

You may or may not have heard the new buzz about promises being introduced into JavaScript and if you don’t know what they are, you’re not alone.  I’ll attempt to explain what they are and why you should or maybe shouldn’t care about them.  First let’s understand what promises are.

Promise defined: “The Promise interface represents a proxy for a value not necessarily known at its creation time. It allows you to associate handlers to an asynchronous action’s eventual success or failure. This let asynchronous methods to return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.”

Basically, it allows you to setup chaining for a value or values and determine a functional response.  For example, let’s say you need to get two values from two separate AJAX calls, but you don’t want to proceed unless both have loaded correctly and if either fails, you want to bail out of the entire thing.  Although not an optimum approach, this will serve as a more or less real world problem.  Consider the following code:

 

var first_call = false;
var second_call = false;
 
//make the first call
$.ajax({
    url: "/some/page",
    success: function(data){
        //set a success variable
        first_call = true;
    }
});
 
//make the second call
$.ajax({
    url: "/some/other-page",
    success: function(data){
        //set a success variable
        second_call = true;
    }
});
 
if(first_call && second_call){
    //we're good to go - do something
}
else{
    //ruh roh - bail out!
}

 

Now obviously, the above code isn’t fantastic but it will suit our needs for now.  Let’s walk through it.  The first ajax call if successful sets the first_call variable to true and the same goes for the second.  If all is good, we can proceed and do what we need to, otherwise we execute our bail out code.  So now let’s check out the same functional code executed with promises:

$.when( $.ajax("/some/page"), $.ajax("/some/other-page") )
    .done(function(first_call, second_call){
        //we're good to go - do something
    })
    .fail(function(){
        //ruh roh - bail out!
    });

So, looking at this latest example we see not only is the code much more compact, but now we can chain even more calls together, no use of outside variables for state checking and still we end up in the same place.  This is the power that promises provide you.  In the above example, we have implemented jQuery’s $.when call which will take a list of operations as the arguments.  For each operation, it will return the value into the done() function as the ordered arguments (ie. done(first_call_data, second_call_data, …)).  If a failure occurs for any of the calls, the fail() method is invoked where we can make use of our bail code and either try again, display an error message, etc.  If we wanted to add more calls to this promise we would do so by adding them directly to the when() function and creating the corresponding argument in the done() method.

$.when(
    $.ajax("/some/page"),
    $.ajax("/some/other-page"),
    $.ajax("/some/other-other-page"),
    $.ajax("/and/so/on")
    )
    .done(function(first_call, second_call, third_call, fourth_call){
        //we're good to go - do something
    })
    .fail(function(){
        //ruh roh - bail out!
    });

We can continue to chain $.when calls together to simply an otherwise complex system of dependencies.  Promises also provide us with a way of implementing our own custom promise behavior by taking advantage of methods such as .reject() .resolve() and .state().  However, this is a bit beyond the scope of this article.  For more information regarding jQuery promises have a look at:

Promise – http://api.jquery.com/promise/

Deferred Object – http://api.jquery.com/category/deferred-object/

D3 Drag And Drop

Implementing drag and drop in D3 (http://d3js.org/) is a pretty simple task when you know how to do it, the following is a walkthrough from setup to execution and the events along the way.

First thing we are going to want to do is setup our drag behavior.  This is the object that will be responsible for handling the actual drag and drop, events and will be added to the call chain of the objects of which we want to allow the drag and drop behavior.

var drag = d3.behavior.drag();

The above statement initializes a new instance of the drag behavior.  We can use it to bind this behavior to the call chain of other objects.  Let’s assume we want to allow all nodes having class “draggable” to have this drag and drop behavior.  To do this we simply add the drag behavior we just instantiated to the call chain of the objects:

var drag = d3.behavior.drag();
d3.selectAll(".draggable").call(drag);

It’s that simple, now all objects containing the “draggable” class will now have this behavior.  But what if we need to do something a bit more complex?  What if we need to have other things happen along the way, update other areas during a drag, initialize or change variables on start and end drag.

var drag = d3.behavior.drag()
    .on("dragstart", function(){
        //do some drag start stuff...
    })
    .on("drag", function(){
        //hey we're dragging, let's update some stuff
    })
    .on("dragend", function(){
        //we're done, end some stuff
    });

As you would expect, each on(…) call defines a hook into the event chain of the drag behavior allowing you to customize the behavior as you see fit.

Web Developer Essential Tools

Foreword

The following highlights what I believe to be the best tools for web development and best of all, they’re all free.  This is a living reference which will be updated as new and better tools are found.  Feedback and suggestions are always welcome.

The List

Google Chrome

Google Chrome

Google Chrome

Light, extremely fast, jam packed with features and a debugger that makes short work of CSS and JavaScript.  The ability to right click inspect an element, change CSS values live in the DOM using up, down arrows or by entering values directly make this an essential tool for web development.

Get Google Chrome

ColorPic

ColorPic

ColorPic

Fantastic color picking tool which allows for obtaining the color values for anything on the screen.  Creation and loading of palettes, values can be slider modified for easy lighting or darkening of tones.  Shortcuts make color selection a cinch.  A must have tool.

Get ColorPic

Tape: Google Chrome Extension

Tape: Google Chrome Extension

Tape: Google Chrome Extension

You know that problem you have in CSS where you’re trying to line up elements either horizontally or vertically and you end up using paper to see if the alignment is correct, well you can forget about doing that ever again.  The Tape plugin allows you to easily place lines on the screen, then you can adjust your CSS to match.

Get Tape Extension

XML Tree: Google Chrome Extension

XML Tree: Google Chrome Extension

XML Tree: Google Chrome Extension

Display XML, RSS any form of node tree in a collapsible human readable format.

Get XML Tree Extension

Awesome Screenshot: Google Chrome Extension

Awesome Screenshot: Google Chrome Extension

Awesome Screenshot: Google Chrome Extension

Quickly screen grab what’s being displayed in the browser, draw, blur, annotate, write, etc. all from within the browser. Save when you’re done either locally or in the cloud.

Get Awesome Extension

LightTable

LightTable

LightTable

LightTable is one of the most robust and unique editors I have ever used.  Extremely powerful, easily customized with more features than I can list here.

Get LightTable

GIMP

GIMP

GIMP

If you’re used to Photoshop, it will take a little bit of a learning curve to get used to GIMP’s shortcuts and approach to image manipulation. However, once you get used to the shortcuts and image editing as a whole, you won’t want to go back. Select an area, resize the selection area by mouse or by shrink or grow amounts, copy then shortcut paste into a new image frame, fast. No more, click save, select extension type from a drop down, confirm, confirm, confirm. Instead, shortcut for save, enter filename with the extension (.png, .jpg, .gif, etc.), hit enter, enter, done. Made for rapid manipulation of images, tons of plugins, filters, great tool.

Get GIMP

Advanced JavaScript Notation

Forword

The following javascript examples and notation demonstrate a few alternatives to well known methods for common tasks.

Advanced Notation

Tilde Operator

The tilde operator “~” literally equates to “-(n+1)”.  For example:

var a = ~1; //returns -2
var myString = "hello world";
~myString.indexOf("hello"); //returns true

Large Denary Numbers

Large denary numbers can be represented in short hand notation using the “e” operator.  For example:

1e6; //returns 1000000.

Floor Checking

Math.floor is the traditional way to check for floor number values.  There are two other short hand methods for performing the same operation, “0|” and “~~”. For example:

var n = 1.23;
Math.floor(n); //returns 1
~~n; //returns 1
0|n; //returns 1

Infinity

When checking for infinity you can use “Infinity” or you can use “1/0”. For example:

Infinity == 1/0; //returns true;

Comma Chaining

The “,” can be used to chain statements together.  For example:

with(document.body)style.backgroundColor="#fff",style.color="#000"

Rounding

Another way to round numbers up is to use “n+.5|0” which is the equivalent to Math.round.  However, this shortcut only works for positive numbers.  For example:

3.2+0.5|0; //returns 3
3.5+0.5|0; //returns 4

String Linking

Strings have a built in method that will trans form them into a link and return the HTML.  For example:

"godlikemouse".link("http://www.godlikemouse.com"); //returns <a href="http://www.godlikemouse.com">godlikemouse</a>

Bit Shifting

A quick way to divide by 2, or to raise something to the power of two is to shift the value. For example

50>>1; //returns 25
20>>1; //returns 10
2<<1; //returns 4
8<<1; //returns 16

jQuery Quick Start Tutorial

Foreword

The following is a quick crash course in using jQuery.  If you’ve never used jQuery before and want to know to how without reading a ton, this is the tutorial for you.

Getting Started

First download the latest version and include it in a page.  Grab the minified version for speed or if you want to read through the code yourself, grab the uncompressed version.

http://docs.jquery.com/Downloading_jQuery#Download_jQuery

Next simply include the library in your HTML page just like any other JavaScript file.

<script type="text/javascript" src="script/jquery-1.4.4.min.js"></script>

Now we’re ready to start using it.

Dom Traversal

So how do we select a node or nodes.  We have a few different choices, we can use CSS selector syntax, or we can use xpath syntax.  Let’s try an example on the following markup.

<html>
<body>
<div class="container">
<span  id="title">Hello World</span>
</div>
</body>
</html>

To apply a standard CSS selector we could use something like “.container #title{ style }” or just “#title{ style }”.  Same with jQuery, here’s an example:

<script type="text/javascript">
 
$(function(){
    var titleSpan = $(".container #title");
    //title span is now set to the span title node
    titleSpan = $("#title");
    //this does the same as well. 
}); 
 
</script>

Now if you’re unfamiliar with jQuery, the above syntax may look a bit odd but here’s the breakdown.  “$” is an alias of the jQuery object, which is what you’ll use to interact with all jQuery APIs.  The long hand for of the above would look like this:

<script type="text/javascript">
 
$(document).ready(function(){
    ...
});
 
</script>

Both do the same thing, wait until the document has fully loaded, then process the function passed into the ready event.  There are several methods for traversing the DOM.  To view the entire list checkout:

http://api.jquery.com/category/traversing/

DOM Manipulation

So how do we work with the DOM, change it’s contents, etc.  jQuery makes this really easy, and here’s how.  Let’s say we wanted to get the text content of the title node using the following HTML.

<html>
<body>
<div class="container">
<span id="title">Hello World</span>
</div>
</body>
</html>

Here’s all we need to do.

var titleText = $("#title").text();

Boom! Done!  Very easy.  But what about changing the text contents of the node. Again:

$("#title").text("Hello Dolly");

Pie!  So if you pass an argument to the text method, it sets the content, without an argument, it retrieves it.  What if we needed to get the innerHTML value of a node.  Here’s what we do:

var html = $(".container").html();

That’s all there is to it, this example grabs the “container” class and retrieves the html content of the node.  What about setting it you ask? Check it out:

$(".container").html('<span id="footer">Goodbye</span>');

That’s all there is to it.  For more information on DOM manipulation, have a look at:

http://api.jquery.com/category/manipulation/

Working With Events

So now it’s time to be productive.  Let’s do something semi-based in the real world.  Let’s say we have a list of anchors that we want to attach a click event to.  Now the old school approach would be to do something like this:

var els = document.getElementsByTagName("a");
int len = els.length
for(var i=0; i<len; i++){
    if(els[i].className == ".showImage"){
        els[i].onclick = function(event){
            ...
        }
    }
}

This approach would allow us to get all the anchor elements off the page, then iterate each to find a match for class “showImage”, then bind a click event to that node and continue.  Using jQuery the same thing can be done if far less code:

$("a.showImage").click(function(){
    ...
});

Quite a difference, but both perform the same functionality.  In jQuery a selector can return a single or an array of elements depending on the markup and selector syntax used.  If the above looks a little confusing, consider this example:

$("a.showImage").each(function(){
    //this will return all a.showImage and call this each function on a per returned node basis
    //basically, this is a for each
 
    var anchor = $(this); //returns the current iteration object of each
 
    anchor.click(function(){
        ...
    });
});

The above does the same as the example before it.  Difference is the amount of code written and for demonstration purposes you can hopefully better understand what’s going on behind the scenes.

So now we now to to bind events, but what about unbinding events.  This example should help:

$("a.showImage").each(function(){
    var anchor = $(this);
    //bind the click event to the anchor
    anchor.bind("click", function(){
        ...
    });
    //unbind the click event from the anchor
    anchor.unbind("click");
});

When you use “object.click”, it’s the same as calling the “bind” method of the object.  Therefore to remove the “bind”, simply “unbind”.  For more information on handling jQuery events see:

http://api.jquery.com/category/events/

Conclusion

That’s about the gist of it.  The rest you should be able to discover on your own.  If you have any questions or find anything I’ve mentioned here to be confusing, please feel free to ask in the comments.

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”:

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 
    } 
};

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:

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

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:

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

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.