jQuery Roundup: Joconut, jQuery Table Sort, jQuery.pushevent

12 Jun 2012 | By Alex Young | Comments | Tags jquery plugins html5 history pjax tables
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.


Joconut (License: MIT) by Vadim Demedes is an alternative implementation of Chris Wanstrath’s pjax plugin. Joconut is about 1K smaller (I compared them both gzipped and minified myself), and it also loads JavaScript and CSS automatically.

Adding Joconut to a page will cause requests to the current host to load using $.ajax. To maintain history, it uses history.pushState, and degrades to onhashchange. Several internal events can be bound to, which is useful for things like error handling:

$.joconut.on('error', function() {
  alert('Error while loading new page!');

Stupid jQuery Table Sort

Stupid jQuery Table Sort (GitHub: joequery / Stupid-Table-Plugin, License: MIT) by Joseph McCullough is a simple table sorting plugin based around Array.prototype.sort:

As long as you understand basic JavaScript sorting, you can make this plugin do as much or as little as you want.

Callbacks can be supplied for custom sorting based on type. In Joseph’s example, he’s set a th class of type-date, then passed in a date callback:

  'date': function(a,b) {


jQuery.pushevent (License: GPL) by “yeikos” helps manage the order events will be fired. This example causes the order of the events to be swapped:

$('button').on('click.first', function() {
}).on('click.second', function() {

The author also sent in two more plugins:

JS101: Constructor Functions

11 Jun 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner

The ECMAScript 5.1 specification defines the behaviour of calling “built-in” constructors as if they were functions. That means not only can new Array(1, 2) be used, but also Array(1, 2):

When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(...) is equivalent to the object creation expression new Array(...) with the same arguments.

15.4.1 The Array Constructor Called as a Function

Object() is documented as performing a type conversion, and String() also does this:

var a = new String(1);
// { '0': '1' }
var b = String(1);
// '1'

The Date constructor technically performs a type conversion, but this is sometimes a source of confusion for beginners who just want a readable string representation of a date:

var a = new Date(2012, 0, 1);
// Sun, 01 Jan 2012 00:00:00 GMT
Date(2012, 0, 1)
// 'Sun Jun 10 2012 11:28:03 GMT+0100 (BST)'

In the first case, a Date object is returned, in the second a primitive string value is returned instead.

Returning Objects from Constructors

In section 13.2.2, the behaviour of returning objects from constructors is defined:

If Type(result) is Object then return result.

This prevents the constructor from returning an instance, so another object can be returned instead.

function Shape() {
  return {
    x: 1, y: 1

Shape.prototype = {
  move: function() {}

var shape = new Shape();
// TypeError: Object #<Object> has no method 'move'

It’s possible to use instanceof to determine if the constructor has been called as a function:

function Shape() {
  if (this instanceof Shape) {
    // An object is being instantiated
  } else {
    return {
      a: 'b'

Shape.prototype = {
  move: function() {}

var shape = new Shape();

Shape(); // Returns { a: 'b' }

jQuery uses a similar approach to instantiate jQuery.Event objects without requiring the new keyword:

jQuery.Event = function( src, props ) {
  // Allow instantiation without the 'new' keyword
  if ( !(this instanceof jQuery.Event) ) {
    return new jQuery.Event( src, props );

This factory-style behaviour may suit certain APIs – Dojo also uses it in NodeList.


Calling built-in constructors as functions is used for type conversion, but some constructors behave as if the new keyword had been used. To avoid bugs caused by missing new keywords, try to remember that these forms are not equivalent.

When writing constructors, this behaviour can be exploited to create factory-like APIs. That’s because it’s possible to detect when a constructor has been called as a function.

To read more about this topic, searching the ECMAScript specification for “called as a function” is a good starting point.

Physijs, SCION, mmd, Sorting

08 Jun 2012 | By Alex Young | Comments | Tags libraries webgl physics SCXML

Physijs Tutorial


Jerome Etienne has written some introductory tutorials on physics and WebGL. In 3D Physics With Three.js and Physijs, he discusses using Physijs with his tQuery project.

The tutorial includes creating a world with lighting, textures, object spawning, and using collision events.


SCION (License: Apache 2, npm: scion) by Jacob Beard is an implementation of State Chart XML (SCXML).

SCXML provides a declarative markup for Statecharts, a powerful modelling language for developing complex, timed, reactive, state-based systems, and can offer elegant solutions to many problems faced in development of JavaScript-based applications across various domains.

The project’s documentation demonstrates how to use SCXML to implement drag and drop in browsers using XML. SCION can load this XML with scion.urlToModel, then interpret it and connect the relevant event listeners in an asynchronous callback. The project also works with Rhino 1.7R3.


mmd by Alex Lawrence is a small patch to enable AMD modules to function when an AMD implementation isn’t available (or perhaps desired). When the author sent us this project he lamented the fact it’s 143 characters long – three characters over a tweet’s limit.

Can anyone make it shorter?

Sorting - We’re Doing It Wrong

Rodney Rehm has written a detailed guide to sorting in JavaScript: Sorting - We’re Doing It Wrong. He covers sorting different types, sorting strings, sorting DOM elements, boosting jQuery’s performance, and more besides.

The post has some interesting comments about the finer points raised in the article, and Rodney has included some benchmarks on jsPerf.

Preparing for Node 0.8

07 Jun 2012 | By Alex Young | Comments | Tags node

Node 0.8 will be released soon:

v0.8 is around the corner. There’s only 1, maybe 2 more 0.7 releases, and then we’re going stable. Test your stuff against master now!


The API changes are relatively straightforward, as we’ve seen with previous Node releases.

If you’ve been following our Windows and Node posts, then of particular interest is the move to node-gyp as the addon build system. This makes building addons easier for Windows users, but at the same time more people are starting to bundle binaries. I’ve found a few node-gyp modules that build successfully in Windows while researching articles for DailyJS, so hopefully the transition won’t be too painful.

Domains will be included in 0.8 – notice how the documentation already refers to 0.8. I remember reading about domains in Ryan Dahl’s Node v0.8 roadmap:

Domains provide a lightweight isolation mechanism for all i/o related to a particular network connection (e.g. an incoming http request). If an unhandled error is encountered, all i/o local to that particular domain is canceled and all handles are cleaned up.

Isaac Schlueter said it’s likely that 0.8 will include V8 v3.10 rather than 3.11. The last time I checked, Node 0.6 was on V8, and since then V8 has seen performance improvements, bug fixes, and better ECMAScript 5 conformance.


  • If you’re a module author, now is a good time to migrate node-waf projects to node-gyp
  • If possible, tag or branch the last working 0.6 version of your modules so people can still install a legacy version – it’s awkward to run multiple versions of Node in Windows
  • Ensure your test suites pass, and follow the API changes to convert legacy code
  • Update your package.json files to refer to the correct version of Node under the engines property

Node Roundup: Boxcars, password-reset, Kraken

06 Jun 2012 | By Alex Young | Comments | Tags node modules express middleware images
You can send in your Node projects for review through our contact form or @dailyjs.


Boxcars (npm: boxcars) by Azer Koçulu is a library for fetching remote or local resources:

boxcars('http://google.com', '/var/log/foo.log', 'http://github.com')(function(error, homepages) {
  // Prints the homepage of google.com

It can also be used to define collections of resources, or cache them through preloading. The author has included tests written with his highkick and lowkick modules.


password-reset (License: MIT/X11, npm: password-reset) by James Halliday is middleware for dealing with password resets that will work with Express.

It’s built with James’ pony module which sends emails, and a full example including the required Express routes is included in the project’s documentation.


Kraken (License: MIT, npm: kraken) by Przemek Matylla is a client for the Kraken Web Optimizer.

Image URLs or uploads can be optimised using this module, and a Kraken Account is required to use it.

Kraken itself was built with Node, and there are a few details about their implementation on the Kraken About page.

jQuery Roundup: jQuery++, Wtwui, jSignature

05 Jun 2012 | By Alex Young | Comments | Tags jquery plugins svg ui widgets
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.


jQuery++ (GitHub: jupiterjs / jquerypp) from Chicago-based JavaScript consulting firm Bitovi, is a collection of DOM and event-related jQuery plugins. The project’s site has a tool for creating a single file that contains all of the plugins that you want, but they can also be loaded using an AMD module loader like RequireJS.

Highlights include a CSS3 version of $.fn.animate, a text range plugin, swipe gesture support, and a version of jQuery.event.fix that uses ECMAScript 5 getters.

There are discussions about the project on Hacker News:


Wtwui (GitHub: wtw-software / wtwui, License: MIT) from WTW Software is a collection of UI widgets influenced by UIKit by TJ Holowaychuk. It currently includes a dialog, overlays, tooltips, and a confirmation box. It’s built using AMD, so each component can be loaded using RequireJS.

The project is tested with Jasmine, and it includes a build script built with Node.


jSignature (GitHub: willowsystems / jSignature, License: MIT) is a fork of brinley / jSignature with additions and tweaks by Daniel Dotsenko.

jSignature allows signatures to be captured in a browser, and works on touchscreen devices as well. Older version of IE are supported by FlashCanvas. A special effort has been made to capture smooth-looking signatures, and it supports extra editing options like undoing the last stroke.

JS101: Object.create

04 Jun 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner
JS101 is a tutorial series aimed at beginners. Each post is a bite-sized chunk aimed to elucidate JavaScript fundamentals. To read previous posts, view the js101 tag.

The inheritance examples we looked at last week used the form Rectangle.prototype = new Shape(). The reason I like this example is it shows how powerful prototypes are, despite their simplicity. The downside is the constructor for the parent object is executed, which isn’t always what’s desired.

ECMAScript 5 introduced Object.create, which creates new objects based on a prototype object and an additional set of properties.

The main differences between B.prototype = new A(); and B.prototype = Object.create(A.prototype) are as follows:

  • The constructor, A isn’t called, so B remains uninitialised until instantiated
  • Object.create accepts a second argument that causes Object.create to behave as if Object.defineProperties was called

Using Object.create

Last week’s Shape example could be rewritten to use Object.create:

function Shape() {
  this.x = 0;
  this.y = 0;
  console.log('Shape constructor called');

Shape.prototype = {
  move: function(x, y) {
    this.x += x;
    this.y += y;

// Rectangle
function Rectangle() {
  console.log('Rectangle constructor called');
  this.x = 0;
  this.y = 0;

Rectangle.prototype = Object.create(Shape);

Now rectangles can be created with var rect = new Rectangle() and the original Shape constructor won’t be called. This leaves us with a cleaner prototype chain, but what if we still want to call the previous constructor? In this particular example, calling the Shape constructor is desirable because we’ll avoid duplicating some initialisation code.

Calling Constructors

By using the Function.prototype.call or apply methods, it’s entirely possible to call another constructor even when using Object.create. For example:

function Shape() {
  this.x = 0;
  this.y = 0;
  console.log('Shape constructor called');

Shape.prototype = {
  move: function(x, y) {
    this.x += x;
    this.y += y;

// Rectangle
function Rectangle() {
  console.log('Rectangle constructor called');

Rectangle.prototype = Object.create(Shape.prototype);

The fact call and apply take a this parameter (known as ThisBinding in the ECMAScript specification) allows us to reuse constructors where required.

No Inheritance: Object.create(null)

By passing null to Object.create, objects can be created that don’t inherit from anything. By default Object.prototype is used, which has several built-in methods. What if we don’t want to inherit from Object.prototype?

function Shape() {

Shape.prototype = Object.create(null);

var shape = new Shape();

In this example, undefined will be printed – objects created using the Shape constructor inherit from null.

Notice that this is not equivalent:

function Shape() {

Shape.prototype = null;

var shape = new Shape();

This should print something like [Function: toString] rather than undefined.

It’s interesting to think about exactly why this is useful. In An Object is not a Hash, Guillermo Rauch discusses how the properties of Object.prototype can be used to potentially cause security issues, and Object.create(null) was suggested as a suitable means for creating a “clean” object to avoid the problem.

Another point is performance. These Object.create(null) benchmarks demonstrate iterating over various objects, and the Object.create(null) tests run faster than object literals.

However, be very careful when using this approach because so many libraries expect objects to have the standard methods.

The Second Argument to Object.create

According to the Annotated ECMAScript 5 Object.create documentation, passing a second argument behaves as if Object.defineProperties had been called. This method requires a bit of knowledge before it can be used – the properties have to be passed in the expected format.

In this example, Rectangle inherits from Shape and gets a property called animate at the same time:

Rectangle.prototype = Object.create(Rectangle.prototype, {
  animate: {
    value: function() {
      this.animating = true;

var rect = new Rectangle();

Now rect.animate() can be called, just like any other method. Notice that the second argument is in the form { propertyName: { value: function() {} } } – the value property is important and I haven’t arbitrarily picked it. These properties are known as property attributes.

Property attributes can be “named data” and “named attribute” properties. These additional flags can be applied to named data properties:

  • writable: Determines if the property is writable
  • enumerable: Should this property be included in for-in enumeration?
  • configurable: If false, attempts to delete or change the property’s attributes will fail

Although this is new to ECMAScript 5, it adds a much desired level of control to properties and their definition.

Getters and Setters

Property attributes allow JavaScript to support getters and setters with a lightweight syntax:

function Rectangle() {
  this._animating = false;

Rectangle.prototype = Object.create(Shape.prototype, {
  animating: {
    get: function() {
      console.log('Rectangle.prototype.animating get');
      return this._animating;

    set: function(value) {
      console.log('Rectangle.prototype.animating set');
      this._animating = value;

var rect = new Rectangle();

rect.animating = true;

In this example I’ve renamed animating to _animating, but it can still be accessed using rect.animating because I’ve defined an animating property with a get and set method.

This makes it possible to track whenever this value is changed, as illustrated by the console.log calls.

In JavaScript implementations that don’t include Object.create, this second argument may not be supported. The ECMAScript 5 compatibility table by Kangax has a wide range of compatibility tests that can help you decide if it’s safe to use it.

Update Notes

This article has been updated using feedback from the following readers:

  • Sean – Accuracy issues
  • Marcel LaverdetObject.create(null)
  • Ghasem Kiani – Issues with my “super” example (removed)
  • Ti – typo (active should have been animating)

TypedFunc, HTML5 Rubik's Cube, Backbone-Require-Boilerplate

01 Jun 2012 | By Alex Young | Comments | Tags backbone.js html5 games libraries


TypedFunc (License: MIT, npm: TypedFunc) by Christopher de Beer is an interesting library for creating typed functions in JavaScript. By using a chainable API, functions can be created that will validate their inputs automatically:

var TypedFunc = require('TypedFunc');

var setName = (new TypedFunc()).throws('string', {}, function(name) {
  console.log('Setting name:', name);
  return name;


The last call, setName(1), will raise an exception like this:

Error: Invalid Function type. Should return string but returned number.

TypedFunc can also support Node’s function(err, value) style of callbacks, rather than throwing an exception.

HTML5 Rubik’s Cube

Rubiks Cube screenshot

This HTML5 Rubik’s Cube by Diego Ferreiro Val uses YUI and CSS transformations to create a 3D Rubik’s Cube. It can also solve itself, and the arrow buttons will undo or redo the last move.

The author has written a detailed tutorial about how he developed it here: Tutorial: Rubik’s cube with HTML5 (CSS3 + JavaScript).


I know there’s a lot of boilerplates out there, but Greg Franko has put a lot of effort into Backbone-Require-Boilerplate (License: MIT).

It’s designed to encourage sharing code between desktop and mobile sites, and includes a recent version of RequireJS that supports loading non-AMD libraries.

Windows and Node: Event Logs

31 May 2012 | By Alex Young | Comments | Tags node tutorials windows logging windows-and-node
To read previous posts in this series, view the windows-and-node tag.

Windows has event logs with three categories: System, Application, and Security. These are known as “sources” in Windows terminology, and since NT 4.0 it’s been possible to create custom sources as well. Pretty much every version of Windows I’ve ever seen has included an Event Viewer utility, which can be used to view and manipulate logs.

Event logs are useful in Windows for the same reasons as syslog in Unix. Logging messages from background services is one of the most obvious examples, particularly as Node seems like a promising platform for developing Windows services.

In Node this requires an addon, because native bindings are needed to communicate with the eventlog service. Windows Event Log Js (GitHub: jfromaniello / windowseventlogjs, License: MIT, npm: windows-eventlog) by José F. Romaniello is one such addon.

On a related note, José has also written a great tutorial on how to create Node addons for Windows using Visual Studio, it’s got detailed instructions and screenshots with full sample code: Writing your first native module for node.js on Windows.

To use this module open cmd.exe and install the module:

npm install windows-eventlog

Now create a simple script to write some test messages:

var EventLog = require('windows-eventlog').EventLog
  , logger = new EventLog('dailyjs-logs');

logger.log('Hello from DailyJS');

This won’t run yet, however. Start another cmd.exe, but this time right-click the icon and select “Run as administrator”:

Run as administrator

Now the example above should run correctly. Open Event Viewer, then select “Windows Logs”, “Application”, and look for logs with the source dailyjs-logs (assuming you didn’t change it). You should see something like this:

Event Viewer

If portability with existing Unix software is required, then check out José’s transport for Winston that uses this module.

Node Roundup: Blade, HighKick, Spellcheck

30 May 2012 | By Alex Young | Comments | Tags node modules addons templating
You can send in your Node projects for review through our contact form or @dailyjs.


Blade (License, npm: blade) by Blake Miner is a Jade-inspired template compiler:

In Blade, there are no “mixins” or partial templates. There are only functions, and they work just like regular JavaScript functions that you’ve come to know and love.

It’s based on PEG.js and UglifyJS. I think it’s extremely interesting to see a Jade-like PEG (parsing expression grammar), which is in blade-grammer.pegjs.

The functions that Blade produces take a callback that gets an error and HTML, so in that sense the API feels idiomatic:

    'nav': {
        'Home': '/',
        'About Us': '/about',
        'Contact': '/contact'
}, function(err, html) {
    if(err) throw err;

The author has also included Express middleware, client-side support, and there are some simple unit tests as well.


HighKick (npm: highkick) by Azer Koculu is a lightweight test runner. It’ll take a module and execute any method that starts with test, which is more similar to the CommonJS Unit Testing specification than most of the popular Node test frameworks.

Functions can be run before and after each test, or the entire module. There’s also an asynchronous mode for running tests asynchronously.

Azer has been using it to test his own modules, so you can check out some of his examples on GitHub.


Spellcheck (License: MIT, npm: spellcheck) by Brian White is an asynchronous Hunspell addon. This is the same library that OpenOffice uses, as well as Chrome.

You’ll need dictionaries and affix files to get it to work, and the author has provided a link to these at the OpenOffice Wiki, under Dictionaries.

jQuery Roundup: cookieConsent, Timing, Tagit

29 May 2012 | By Alex Young | Comments | Tags jquery jqueryui cookies timers
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.


The EU doesnt understand cookies

jquery.cookieConsent (License: MIT) by Tom Ashworth is a drop-in plugin for satisfying new EU policies regarding cookies. By running $.cookieConsent(), this plugin will display a banner. Once the banner is clicked, a cookie called cookieConsent will be set so the banner won’t need to annoy the visitor again.

The irony of setting a cookie to hide a message informing users about the use of cookies is amusing, but that’s not Tom’s fault so much as the nature of the beast.


Timing (GitHub: creativecouple / jquery-timing, License: MIT) by Peter Liske is a wrapper around setTimeout and other timer functions. It has a chainable API, so it’s easy to create complex scenarios without too much code:



Tagit (GitHub: hailwood / jQuery-Tagit, License: CC BY-SA 3.0) by Matthew Hailwood uses jQuery UI’s Autocomplete to present an alternative way of entering lists. Features include:

  • Automatically adding partially typed tags if the control loses focus
  • Friendly behaviour when deleting tags
  • Sortable items using drag and drop

The sortable version only requires a single option to work:

$(selector).tagit({ tagSource: ['one', 'two', 'three'], sortable: 'handle' });

It’s quite easy to theme this plugin, and the author has kindly bundled quite a few CSS files.

JS101: Inheritance

28 May 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner
JS101 is a tutorial series aimed at beginners. Each post is a bite-sized chunk aimed to elucidate JavaScript fundamentals. To read previous posts, view the js101 tag.

Inheritance Chains and Constructors

As we saw last week, JavaScript objects have a prototype property, which is designed to facilitate inheritance. An object’s prototype property can be set to an instance of another object to create an inheritance chain:

function Shape(name) {
  this.x = 0;
  this.y = 0;
  this.name = name;
  console.log('Shape constructor called');

Shape.prototype = {
  move: function(x, y) {
    this.x += x;
    this.y += y;

  toString: function() {
    return 'name: ' + this.name + ', at x: ' + this.x + ', y:' + this.y;

// Rectangle
function Rectangle(name) {
  this.name = name;
  console.log('Rectangle constructor called');

Rectangle.prototype = new Shape();

var rect = new Rectangle('Player 1');
rect.move(1, 1);
console.log(rect instanceof Rectangle);

Running this will display the following output:

Shape constructor called
Rectangle constructor called
name: Player 1, at x: 1, y:1

Notice that both the Shape and Rectangle constructors are called. This is because of the line Rectangle.prototype = new Shape(); – the parent object’s constructor isn’t actually automatically called as a result of new Rectangle(). This is why I’ve duplicated the this.name = name line in both constructors.

Also notice that rect.move and rect.toString call the methods from Shape.prototype. When the interpreter checks for a property, it will examine the current object for it. If no such property is found, the prototype for the object is checked, and so on. This is the prototype chain:

First the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.

Annotated ECMAScript 5.1

Calling Parent Methods

If we wanted Rectangle to have a different move method, but reuse the original in Shape, then it’s entirely possible to do so using Function.prototype.apply:

Rectangle.prototype.move = function(x, y) {
  console.log('Super method called');
  Shape.prototype.move.apply(this, arguments);

Even though Shape.prototype.move.apply looks complicated, it’s actually very simple if we break it down:

  1. We want to call the move method from Shape
  2. This method is stored in Shape.prototype.move
  3. Since this is a Function, there are several methods available to us (functions are objects!)
  4. The apply method in particular allows us to call the function without creating a new instance
  5. It also allows us to provide our own value for this, and an array of arguments

The arguments object is created by the interpreter when a function is executed. The this object is a whole other story – so far I’ve been assuming you have intuitively understood what it is, but we’ll look at it in more detail in the next part.


Ender Roundup: tablesort.js, Moment.js, jwerty, SelectNav.js, ender-events, ender-assert, Categorizr.js, Arbiter

You can send in your Ender-related projects for review through our contact form or @dailyjs. Be sure to also update the Ender package list page on the Ender wiki.


tablesort.js (GitHub: tristen/tablesort, npm / Ender: tablesort) by Tristen Brown is a dependency-free sorting library for HTML tables. tablesort.js can be invoked stand-alone via new Tablesort(document.getElementById('table-id')) or $('#table-id').tablesort() method from within Ender.

Olivier Vaillancourt has written a small review of tablesort.js for use in Ender on Twitter Bootstrap tables.


Moment.js (GitHub: timrwood/moment, npm / Ender: moment) by Tim Wood is small, yet very comprehensive date and time handling library.


Moment.js was mentioned last year on DailyJS but it now has a simple Ender bridge allowing you to pack it neatly into Ender builds for use via $.ender(). Plus, it’s an absolutely fantastic library for anything date/time related so it’s worth mentioning again. Be sure to scan the docs to see just how much this library can do.

$.moment().add('hours', 1).fromNow(); // "1 hour ago"

// manipulate
$.moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0);

// parse dates in different formats
var day = $.moment("12-25-1995", "MM-DD-YYYY");

var a = $.moment([2010, 1, 14, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
a.format("ddd, hA"); // "Sun, 3PM"

// operate on different 'moment' objects
var a = $.moment([2007, 0]);
var b = $.moment([2008, 5]);
a.diff(b, 'years'); // 1
a.diff(b, 'years', true); // 1.5

The project maintainers also follow a rigorous release methodology, making great use of git branches, something that is not often found on smaller open source libraries.


jwerty (GitHub: keithamus/jwerty, Licence: MIT, npm / Ender: jwerty) by Keith Cirkel is a small keyboard event handling library which can bind, fire and assert key combination strings against elements and events.

$.key('ctrl+shift+P', function () { [...] });
$.key('⌃+⇧+P', function () { [...] });

// specify optional keys
$.key('⌃+⇧+P/⌘+⇧+P', function () { [...] });

// key sequences
$.key('↑,↑,↓,↓,←,→,←,→,B,A,↩', function () { [...] });

// pass in a selector to bind a shortcut local to that element
$.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, 'input.email', '#myForm');

// use `$.event` as a decorator, to bind events your own way
$('#myinput').bind('keydown', $.keyEvent('⌃+⇧+P/⌘+⇧+P', function () { [...] }));

// use `$.isKey` to check a key combo against a keyboard event
function (event) {
    if ( $.isKey('⌃+⇧+P', event) ) { [...] }

// use `$.fireKey` to send keyboard events to other places
$.fireKey('enter', 'input:first-child', '#myForm');


SelectNav.js (GitHub: lukaszfiszer/selectnav.js, npm / Ender: selectnav.js) by Lukasz Fiszer is a small library that will convert your website’s navigation into a <select> menu. Used together with media queries it helps you to create a space saving, responsive navigation for small screen devices. SelectNav.js is inspired by TinyNav.js for jQuery.

ender-events and ender-assert

ender-events (GitHub: amccollum/ender-events, Licence: MIT, npm / Ender: ender-events) and ender-assert (GitHub: amccollum/ender-assert, Licence: MIT, npm / Ender: ender-assert) are two packages by Andrew McCollum, previously bundled in his node-compat library. ender-events gives you an implementation of the NodeJS EventEmitter class in your browser, while ender-assert gives you a browser version of the NodeJS assert module.

Andrew also has a tiny extension to Bonzo, the DOM utility included in Ender’s starter pack (The Jeesh), named ender-remove that simply triggers a ‘remove’ event when nodes are removed from the DOM. Which can be helpful for performing clean-up actions.


Categorizr.js (GitHub: Skookum/categorizr.js, Licence: MIT, npm / Ender: categorizr) by Dustan Kasten is a JavaScript port of the Categorizr PHP script by Brett Jankord.

Categorizr gives you $.isDesktop() $.isTablet() $.isTV() $.isMobile() methods to determine the current device.


Arbiter (GitHub: iamdustan/arbiter, Licence: MIT, npm / Ender: arbiter) also by Dustan Kasten is a tiny library for managing the HTML5 history interface via pushState(), using AJAX requests to load new content upon request.

Windows and Node: Writing Portable Code

24 May 2012 | By Alex Young | Comments | Tags node tutorials windows windows-and-node

I’ve been surveying popular Node modules and the nodejs Google Group to find common portability issues people have found when testing modules in Windows.

For the most part, Node code seems very portable – there are only a few problem areas that seem to crop up frequently. Let’s take a look at these problems and the solutions so we can write code that runs everywhere.

Platform-Specific Code

Despite Node code’s inherent portability, there are times when platform-specific code is required. This is dealt with in Node’s core modules like this:

var isWindows = process.platform === 'win32';

if (isWindows) {
  // Windows-specific code

This example is based on path.js.

For more detailed information on the operating system, the os module can come in handy.

Nodes OS module in Windows

File System

Windows can actually accept backslashes or forward slashes as a path separator. This means you don’t need to change all of your require calls to use different slashes; most things should just work. There are a few cases where we need to be careful, however, particularly if a path name is absolute or it’s going to be displayed somewhere.

One common issue I’ve found is where the developer has made certain assumptions about the structure of absolute paths. In a commit to Express, Fixed absolute path checking on windows, we can see where the authors have adapted a method called isAbsolute to support Windows:

exports.isAbsolute = function(path){
  if ('/' == path[0]) return true;
  if (':' == path[1] && '\\' == path[2]) return true;

Isaac Schlueter recommends using path.resolve to make relative paths absolute in a cross-platform way.

When dealing with fragments of paths, using path.join will automatically insert the correct slash based on platform. For example, the Windows version will insert backslashes:

var joined = paths.join('\\');

Notice that JavaScript strings require two backslashes because one acts as an escape, so when working with Windows path names don’t be surprised if there are lot of double slashes.

Another big source of Windows issues is fs.watch. This module is routinely used by programs that watch for file system changes. Node’s documentation makes it clear that the API isn’t portable, so the slower but more compatible fs.watchFile can be used instead.

In this patch for the Derby web framework, we can see where the developers opted to branch based on process.platform to use fs.watchFile in Windows, but fs.watch elsewhere.

Text Interfaces

Be aware that not everybody has a super-fancy UTF-8 terminal that supports colours. Certain programs depend on text output, but people may have trouble seeing it correctly if your program relies on symbols their terminal or font doesn’t support.

Mocha is a good example of such a program, and in the issue Ability to configure passed/failed checkmarks for the spec reporter, we can see where someone has struggled to read the output with cmd.exe.


Assuming certain environmental variables will exist (or mean the same thing) on every platform is a good way to create portability headaches.

James Halliday’s Browserify had its fair share of Windows issues, which was problematic due to several other popular modules depending on it.

This commit to Browserify demonstrates a fix Christopher Bennage submitted that replaces calls to process.env.HOME with the following:

var home = (process.env.HOME || process.env.USERPROFILE);

I tried this in Windows 7 and found process.env.HOME wasn’t set, but process.env.USERPROFILE worked as expected.


Node’s TCP sockets are portable, but Unix domain sockets are not. However, Windows has named pipes. The following code is almost exactly the same as the Unix equivalent, it just has a different path to the named pipe:

var net = require('net');

net.createServer(function(socket) {

Notice the escaped backslashes – forgetting to insert them here will raise a confusing EACCESS error. In node/test/common.js, there’s a branch based on platform to set the name of the pipe so it works in Windows and Unix:

if (process.platform === 'win32') {
  exports.PIPE = '\\\\.\\pipe\\libuv-test';
} else {
  exports.PIPE = exports.tmpDir + '/test.sock';


Node Roundup: Uptime, mmmagic, nodeflix, opt

23 May 2012 | By Alex Young | Comments | Tags node modules apps cli express unix
You can send in your Node projects for review through our contact form or @dailyjs.


Uptime screenshot

Uptime (GitHub: fzaninotto / uptime, License: MIT, npm: node-uptime) by Francois Zaninotto is an Express app for remote server monitoring. It’s built with Mongoose, Bootstrap, ejs, Socket.IO, and jQuery.

To use the app, a YAML configuration file must be created for the sites you want to monitor. It seems like JSON would have been a more natural choice, but it’s pretty easy to get started and there are examples in the documentation.

I’m always looking for open source Express applications, so keep them coming!


mmmagic (License: MIT, npm: mmmagic) by Brian White is a Node addon for libmagic, as used by the file) command. It’s asynchronous, and can provide the MIME type for a file (as well as other metadata):

var mmm = require('mmmagic')
  , Magic = mmm.Magic;

var magic = new Magic(mmm.MAGIC_MIME_TYPE);
magic.detectFile('/usr/bin/env', function(err, result) {
  if (err) throw err;

It’s currently built with node-waf (rather than gyp), but the author has included a Windows binary.


Nodeflix (License: MIT, npm: nodeflix) by Johnathan Leppert is a Netflix API client:

n.get('/catalog/people', { term: 'DeNiro' }, function(data) {

I’ve noticed quite a few Node media-related modules cropping up, and with the continually improving Windows support it seems like Node is becoming a strong platform for home theatre-related application development. Is there a Node XBMC alternative yet?


opt (License: New BSD License, npm: opt) by R. S. Doiel is an options parser that can also load configuration files. It can generate usage based on the supplied parameters, but has a slightly different API to the other option parsing modules I’ve looked at – callbacks are tied to each option instead of working with a parsed set of options:

#!/usr/bin/env node
var opt = require('opt')
  , args;

function test(param) {
  if (param) {
    console.log('--test parameter:', param);
  } else {
    console.log('No parameter supplied to --test');

opt.setup('Simple test script.');
opt.set(['-h', '--help'], opt.usage, 'Show help');
opt.set(['-t', '--test'], test, 'Run test');


This is quite different to how Commander.js works, for example.

jQuery Roundup: jQuery UI 1.9 Milestone 8, Chico UI, Complexify

22 May 2012 | By Alex Young | Comments | Tags jquery jqueryui libraries security
Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

jQuery UI 1.9 Milestone 8

jQuery UI 1.9 Milestone 8 has been released. The major change in this release is a redesign of the Position utility script.

There are also bug fixes and accessibility improvements.

Chico UI

Chico banner

Chico UI (GitHub: mercadolibre / chico, License: MIT) from MercadoLibre is a set of UI widgets built with jQuery. The project includes demos with documentation for each widget, I’ve selected a few interesting ones here but there are a lot more:

There’s also Chico Mesh for creating CSS column-based layouts, and some tutorials on Chico.

The mix of JavaScript widgets and reusable layout CSS reminds me of a combination of jQuery UI and Bootstrap. I haven’t seen Chico before, but the authors have been committing frequently to the GitHub project over the last two years, so at this point it seems relatively mature.



Complexify (GitHub: danpalmer / jquery.complexify.js, License: WTFPL v2) by Dan Palmer is a password complexity checker. It’s used like this:

$('#password').complexify({ minimumChars: 8 }, function(valid, complexity) {
  // valid: Password is the right length
  // complexity: Password complexity rated as a percentage

The algorithm Dan’s written to rate complexity is based on blocks of Unicode:

The rationale behind this is that in an attacker were wanting to include Japanese passwords in his attack, he/she may choose to include the Hiragana set in his/her attack, but not the Katakana set. Complexify divides Unicode into 94 appropriately grouped sets.

The main driver behind the algorithm is to try to distinguish between complex passwords, and passwords that have the illusion of complexity due to security policies.

JS101: Prototypes

21 May 2012 | By Alex Young | Comments | Tags js101 tutorials language beginner
JS101 is a tutorial series aimed at beginners. Each post is a bite-sized chunk aimed to elucidate JavaScript fundamentals. To read previous posts, view the js101 tag.

After spending years studying object oriented programming, adapting to JavaScript can be frustrating. In particular, the lack of a class keyword is a source of confusion. However, JavaScript’s design needn’t be a hindrance – mastering its prototype-based inheritance will improve your understanding of the language.

The first thing to realise is there should be a distinction between object-oriented programming and class-oriented. JavaScript gives us the tools we need to do most of the things languages with classes can do – we just need to learn how to use it properly.

Let’s take a brief look at the prototype property to see how it can deepen our knowledge of JavaScript.

The prototype Property

The prototype property is an internal property, and it’s designed to be used to implement inheritance. What we mean by “inheritance” here is a specific form of inheritance. Because both state and methods are carried by objects, then we can say that structure, behaviour, and state are all inherited (ES5: Objects). This is in contrast to class-based languages, where state is carried by instances and methods are carried by classes.

A constructor is a function that has a property named prototype:

function Animal() {


This displays {} – the Animal object has a prototype property, but there’s nothing user-defined in it yet. We’re free to add values and methods as we please:

function Animal() {

Animal.prototype.type = 'Unknown';
Animal.prototype.weight = 0;
Animal.prototype.weightUnits = 'kg';

Animal.prototype.toString = function() {
  return this.type + ', ' + this.weight + this.weightUnits;

var molly = new Animal();
molly.type = 'Dog';
molly.weight = 28;


This would display “Dog, 28kg”. We can group these assignments together by using an object literal:

function Animal() {

Animal.prototype = {
  type: 'Unknown',
  weight: 0,
  weightUnits: 'kg',

  toString: function() {
    return this.type + ', ' + this.weight + this.weightUnits;

This shouldn’t look too different from the classes you might be more familiar with.

Dynamic Prototypes

Properties can be added to objects dynamically, simply by assigning values:

var molly = new Animal()
  , harley = new Animal();

molly.type = 'Dog';
molly.weight = 28;

harley.type = 'Dog';
harley.weight = 38;
harley.name = 'Harley';


// { type: 'Dog', weight: 28 }
// { type: 'Dog', weight: 38, name: 'Harley' }

Adding the name property here only affects that instance. However, the constructor’s prototype can be changed, and this will affect objects made with that prototype:

Animal.prototype.weightUnits = 'oz';

// Now displays 'Dog, 28oz'

This is why people boast that their libraries don’t touch native prototypes, or only do so safely – it’s entirely possible to change the expected built-in functionality of objects like String to do unsafe things:

String.prototype.match = function() {
  return true;


This returns true, so I’ve now succeeded in breaking a fundamental method that many JavaScript programs rely on.

Modifying native prototypes isn’t always bad; people use it for useful things like patching support for more modern versions of ECMAScript in older browsers.

What happens if we replace the prototype property?

var molly = new Animal()
  , harley;

molly.type = 'Dog';
molly.weight = 28;

Animal.prototype = {
  toString: function() {
    return '...';

harley = new Animal;
harley.type = 'Dog';
harley.weight = 38;


// Dog, 28kg
// ...

Despite the fact changing a prototype affects all of the instances, replacing a constructor’s prototype entirely does not affect older instances. Why? Well, instances have a reference to the prototype rather than a discrete copy. Think of it like this: each instance created by the new keyword is connected to the original prototype.

Next Week

In the spirit of keeping this post bite-sized, I’ll finish here. Next week we’ll look at prototype chains and inheritance in more detail.


Page, testr.js, screenfull.js

18 May 2012 | By Alex Young | Comments | Tags testing fullscreen routing


If I had to place a bet on the most activity by one person on GitHub, I’d bet on TJ Holowaychuk. His latest project is Page.js (GitHub: visionmedia / page.js, npm: page), which is a client-side router. The routing syntax works like Express, so variables are denoted by :name, and the * route can be used to catch 404s. In this case, 404 is open to interpretation.

page('/', index)
page('/user/:user', show)
page('/user/:user/edit', edit)
page('/user/:user/album', album)
page('/user/:user/album/sort', sort)
page('\*', notfound)

It’s actually a very lightweight project, based around pushState, but it includes detailed comments and Mocha tests.


testr.js (License: MIT) by Matt Fysh is for unit testing RequireJS modules. Use it with your favourite test framework to test both stubbed and script-loaded dependencies:

testr('path/to/module', stubs);
testr('path/to/module', useExternal);
testr('path/to/module', stubs, useExternal);

The author has written some projects that use testr.js – asq and after both use it with Jasmine.


screenfull.js (GitHub: sindresorhus / screenfull.js, License: MIT) by Sindre Sorhus is another wrapper around the Fullscreen API. The semantics are similar to the specification, but a lot simpler – the README has a comparison with “vanilla” JavaScript which is several lines of code. Using screenfull.js, only screenfull.request() is required to trigger fullscreen mode.

The library can do other things as well: a single element can be fullscreened, or events can be used to detect a change to fullscreen mode.

Windows and Node: Addons

17 May 2012 | By Alex Young | Comments | Tags node tutorials windows addons gyp windows-and-node

In this article we’re going to look at addons. If you’re a Node developer working in Windows then this article should give you enough background to at least understand the basic issues surrounding addons, and install them using npm.

Addons are something Unix-based Node developers generally have little trouble with. However, the history of addon support in Windows has been a little bit turbulent. We’ve seen various solutions come and go – most notably node-waf and Cygwin – but the community has now settled on node-gyp by Nathan Rajlich.

Hint: Addons use C or C++ libraries. Node modules may include both addons and JavaScript code.

Isaac Schlueter summarised it in this comment:

Node-waf doesn’t work on Windows. We’re working on a solution that will make it easier to get a build toolchain in Windows based on node-gyp. Many packages will have to be updated to use this instead, so we’re trying to make it as easy a transition as possible.

Installing a Module with Native Code

The fibers module uses node-gyp for building its native components. However, the module’s author, Marcel Laverdet, has packaged it in an extremely effective way. Rather than force everybody to build the module, he’s included binaries in the npm package. These are not present in the GitHub repository, but are available through npm. This includes both 32 and 64 bit versions.

node-fibers installation in Windows

Therefore, simply running npm install fibers should result in a working module in Windows. The compressed archive on npm actually includes Linux, Mac OS, and Windows binaries, for example: bin/win32-ia32/fibers.node.

Building a Module in Windows

As an exercise, let’s build the fibers module. I picked this one because I already know it works – although there are other modules built with node-gyp, they don’t all build correctly in Windows yet.

Building the module requires a few dependencies:

  • A global installation of node-gyp
  • Python 2.7
  • Microsoft Visual Studio (“Express” is free)

Installing node-gyp

The node-gyp module is easy to install, but just make sure it’s installed globally so it’ll be in your %PATH%:

npm install -g node-gyp

Installing Python

GYP, or Generate Your Projects, is a build system that uses Python. GypUserDocumentation covers the basics, but from our perspective we just need a working version of Python 2.7.x to use it.

I installed Python 2.7.3 using the MSI installer.

Installing Microsoft Visual Studio

Microsoft provides a free edition of Visual Studio called Visual Studio 2010 Express. I downloaded the ISO and extracted the ISO using 7-Zip. It’s 694 MB, so you might want to brew a suitable hot drink while it’s downloading.

Installing Visual C++

Fortunately, Microsoft provide this suite of tools and compilers for free with no user registration.

Running Microsofts IDE

Building the Module

I downloaded the latest zip of node-fibers from GitHub, opened Command Prompt, changed directory to the path of the extracted zip, then ran the following:

set PATH=%PATH%;C:\Python27
node-gyp configure
node-gyp build

Building the fibers module

Once that was done I ran npm test, and the tests all passed. I found it quite satisfying to see Microsoft’s compiler actually build something, and although it’s not necessary to build the fibers module this way, there are other modules out there that don’t include binaries in npm.


Hopefully you now appreciate a little bit about how addons are built in Windows. Although previously the situation was confusing, the community is starting to convert modules to build with node-gyp.

I suspect there will be cases where native code can’t be shipped as binaries due to licensing constraints, but it would be encouraging to see more addons include binaries for Windows.

Node Roundup: express-soap2json, cb, ApiServer

16 May 2012 | By Alex Young | Comments | Tags node modules
You can send in your Node projects for review through our contact form or @dailyjs.


SOAP might not be the most exciting technology to work with, but if you like Node and Express then express-soap2json (License: MIT, npm: express-soap2json) by Tony Sokhon can make it a little bit easier to work with.

By wrapping around a SOAP service, express-soap2json creates a JSON/HTTP proxy. It’s built using the soap module by Vinay Pulim. Tony has included some Mocha tests, and the README has some basic documentation.

An Alternative to Node’s console.time

In A Powerful Alternative to Node’s console.time(), Dmitri Melikyan discusses using his Nodetime profiler in place of console.time and console.timeEnd.

What if you want to know more about what happens in-between, say CPU time or other nested network of file operations in microsecods precision?


cb (License: MIT, npm: cb) by Jeremy Martin is yet another control flow library. Or is it?

Not exactly. There are literally hundreds of libraries available for easing some of the pains associated with the continuation passing style, and most of them do a pretty good job at this.

Rather than compete with these libraries, cb() focuses on a much narrower range of problems, and is intended to be complementary to your control flow library (or lack thereof) of choice.

It features timeout and error handling with a chainable API, so the following is possible:

var cb = require('cb')
  , fs = require('fs');

, 'utf8'
, cb(console.log)


ApiServer (GitHub: kilianc / node-apiserver, License: MIT, npm: apiserver) by Kilian Ciuffolo is a modular framework that’s a bit like Restify, but can also be used to make Express-style web applications. Kilian has written his own comparisons with Express and Restify, and it’s compatible with Express middleware even though it’s not built with Connect.

The routing module, apiserver-router, features a caching system, and applications are built using objects. These objects are known as modules, and each method is an API endpoint. It works with plain objects and prototype classes – classes are ideal if the module has a state (Kilian’s example passes in a database reference).

The author has also included a Mocha test suite, and the documentation is pretty solid too.