Category Archives: JavaScript

Zenhance NodeJS MVC Framework Is Alive

A Zend Framework like MVC approach to building NodeJS enterprise applications in an easy to install NodeJS module.

The new Zenhance NodeJS MVC Framework is up and running and available for install.  The entire framework is comprised of a single NPM module and can be installed and running in less that 5 minutes once you have NodeJS installed.  To begin, simply run:

user@computer:$ npm install zenhance

To install the Zenhance module and all of its dependencies

Next, create a server.js file with a single line of code

require('zenhance').run()

Then execute the server.js file with node

user@computer:$ node server.js

That’s all there is to it.  Full documentation and more information is available on Github and on collaboradev at Zenhance.

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 ThreeJS WebGL Plugin

I have previously released a jQuery Rubik’s cube plugin comprised of only HTML, JavaScript and CSS.  Although pretty nifty, there were a few issues with regards to support from some browsers, most notably Firefox and Internet Explorer.  I decided to recreate the plugin using WebGL.  The result is my jquery.cube.threejs.js plugin. As seen below.

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

See the Pen jQuery ThreeJS 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 by the 3×3 cube 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 or data-moves attribute.

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.

This incarnation of the plugin also supports cube sizes of 2×2 up to 9×9 with no issues.  Cubes larger than 9×9 may see some degradation in frame rates depending on the speed of the client devices.

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

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

Storing And Retrieving Objects In HTML5 Local Storage

I’ve recently had the need to store information using HTML5’s local storage API.  To my surprise the API itself is geared toward only letting you store strings.  That being said I needed to store and retrieve information in a way that would make it easy to retain types as well as store complete objects.  The following is the approach I used which should help those of you unfamiliar with HTML5 local storage get up to speed on how to use it, as well as introduce a possibly not so obvious way to store complete object information as well as retain basic types.

Basic storage of information is simple.

localStorage["mykey"] = "myvalue";

Retrieval is just as easy.

var myvalue = localStorage["mykey"];

But what about actual types? Hmmm….

localStorage["mykey"] = 42;
var myvalue = localStorage["mykey"]; //returns the string "42"
 
//wait a minute...
 
localStorage["mykey"] = {};
var myvalue = localStorage["mykey"]; //returns the string "[object Object]"

Well crap! I’ve lost my input type and retrieved a string on the other side.  What’s a coder to do?  How about we make it retain our input types, not only that, let’s make it so we can store object types as well.

jQuery has some nice JSON parsing utilities among other things, let’s incorporate that along with a way to serialize objects into JSON strings.  First we’ll need a JSON serializer, better known as a stringifier (No, I didn’t make that up.  That’s actually what it’s called.)

Here’s a simple method which can be used to extend jQuery and allow objects to be stringified.

jQuery.extend({
stringify : function stringify(obj) {
	if(JSON && JSON.stringify)
		return JSON.stringify(obj);
 
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"' + obj + '"';
			return String(obj);
	} else {
		// recurse array or object
		var n, v, json = [], arr = (obj && obj.constructor == Array);
 
		for (n in obj) {
			v = obj[n];
			t = typeof(v);
			if (obj.hasOwnProperty(n)) {
				if (t == "string") v = '"' + v + '"'; else if (t == "object" && v !== null) v = jQuery.stringify(v);
				json.push((arr ? "" : '"' + n + '":') + String(v));
			}
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
}
});

The above code is a very simple stringifier.  There are far more complex ones out there if you do a little searching, but I’ve been using this one for quite a while and it has always suited my needs.  Unfortunately however, I don’t remember where I originally found this code.  I didn’t write it, full credit goes to the original author (and if you know who that is please let me know and I’ll add an ownership clause).

Now, if we combine the use of our new stringifier and the use of jQuery’s own $.parseJSON, we should be in business.  Let’s give it a try.

var myvalue = {
first: "Bob",
last: "Dobalina",
age: 52
};
 
//let's store it
localStorage["mykey"] = $.stringify(myvalue);
 
//now let's retrieve it
myvalue = $.parseJSON( localStorage["mykey"] ); //returns actual JSON object

Perfect, now all our types are intact, we can store and retrieve objects ad nauseam, the world is once again a perfect place, birds are singing, no they don’t use Photoshop – super models really look like that and everything that tastes good is actually good for you.  Let’s verify our object types.

var first = myvalue.first; //returns "Bob"
var last = myvalue.last; //returns "Dobalina"
var age = myvalue.age; //returns 52

It’s worth being said that this point as well that local storage does have a size limitation of 5MB based on origin (which if you’re unfamiliar with is scheme + hostname + port).  So keep that in mind as you move forward with storing local information.  Hope this helps and thanks for swinging by.

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/

JavaScript Worker Threads

Ever find yourself needing to do some number crunching, or create an off time rendering hook or perhaps just needing to create a separate thread for some other purpose, this is how you do it.  First things first, we need to create a separate javascript file which will house our thread execution code.  In this example, let’s create a file called “thread.js” and add the following:

function Thread(){
    var _ref = this;
    var _running = null;
 
    _ref.start = function(){
 
        //execution code
        function execute(){
            self.postMessage({
                cmd: "console.log",
                value: "Execute called..."
            });
        }
 
        _running = setInterval(execute, 1000);
    }
 
    _ref.stop = function(){
        clearInterval(_running);
    }
}
 
var thread = new Thread();
 
self.onmessage = function(e){
    thread[e.data.cmd](e.data.args);
}

So here’s what happening in this file.  We’ve created a class called “Thread” and created public methods “start” and “stop”.  Just for an example of functionality we’ve added an execute method loop which is invoked by a setInterval call every second (1000ms).  The “_running” variable is assigned the interval handle and cleared when the “stop” method is called.  Within the “execute” method the postMessage method is called which sends the message over the wall to our main execution script which we will detail below.  Lastly, we create an instance of the Thread class and create an “onmessage” handler to deal with incoming messages sent to our Thread class from over the wall in our main execution script.  Here, the Thread instance variable is invoked with the “cmd” parameter as the method and the “args” parameter as the arguments passed to the invoked method.  So here’s the main execution script that we will use to create an instance of the thread:

 

//create a worker thread
var worker = new Worker("thread.js");
 
//handle messages sent from Thread
worker.onmessage = function(e){
    switch(e.data.cmd){
        case "console.log":
            console.log(e.data.value);
            break;
    }
}
 
//start the Thread
worker.postMessage({cmd: "start"});
 
//stop the Thread after 5 seconds
setInterval(function(){
    worker.postMessage({cmd: "stop"});
}, 5000);

 

So let’s walk through the main script.  We create a instance of the “Worker” class and pass in the script we are going to use as our worker thread, in this case “thread.js”.  Next we setup an onmessage handler to receive messages sent from within our Thread.  Next we send a message with the cmd parameter set to start which over the wall evaluates to “thread.start()”.  Lastly, we setup an interval callback to be invoked after 5 seconds (5000ms) to stop the Thread.  Pie, right?  So now what if we want to add a method to the Thread class that takes in parameters and sends a value back to our main script…let’s do it:

function Thread(){
 
    //existing code omitted here...
 
    _ref.foo = function(args){
        self.postMessage({cmd: "console.log", value: args});
    }
}

So now we’ve added the method “foo” with arguments “args” and in turn we post a message back over the wall to the main script returning the “args” passed in as the value.  Now, let’s add the code to invoke it within our main script:

//existing code omitted here...
 
worker.postMessage({cmd: "foo", args: "bar"});

All we’ve done here is add another “postMessage” call with a “cmd” parameter of “foo” and an “args” parameter of “bar” which evaluates to “thread.foo(‘bar’)” on the other side of the wall within our Thread class.

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.