Inheritance in Node.js

I usually try to avoid using inheritance in JavaScript altogether but sometimes there are situations where using a classic OO-style can make things easier.

Let’s assume we have a class Foo which we want to extend:

function Foo() {
  // constructor code
}
Foo.prototype = {
  bar: function() {
    // do something
  }
};

A common pattern is this:

function Bar() {
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.bar = function() {
  // do something else
};

Using util.inherits()

In contrast to the original definition of Foo this looks quite noisy. In Node.js there’s the util.inherits() function which helps us to write the same thing a little more compact and also creates a constructor property as well as a reference to the super constructor:

function Bar() {
}
util.inherits(Bar, Foo);
Bar.prototype.bar = function() {
  // do something else
};
Bar.prototype.baz = function() {
  // yet another method
};

Passing properties to Object.create()

Still we have to repeat Bar.prototype for each property we want to add. We can overcome this by passing a property descriptor to Object.create():

function Bar() {
}
Bar.prototype = Object.create(Foo.prototype, {
  bar: { value: function() {
    // do something else
  }},
  baz: { value: function() {
    // yet another method
  }}
});

Unfortunately this still looks quite noisy as we have to wrap all our properties into descriptor objects. On the other hand this syntax makes it easy to define getters or setters:

function Bar() {
}
Bar.prototype = Object.create(Foo.prototype, {
  bar: { value: function() {
    // do something else
  }},
  boo: {
    get: function() {
      return this._boo;
    },
    set: function(value) {
      this._boo = value && (''+value).toUpperCase();
    }
  }
});

Otherwise we’d have to call Object.defineProperty('boo', {...}) instead.

The get and set operators

Still this isn’t as concise as it could be. Since JavaScript 1.8.5 the language supports the get and set operators which can be used inside an object literal to define getters and setters:

function Foo() {
  // constructor code
}
Foo.prototype = {
  get boo() {
    return this._boo;
  }
  set boo(value) {
    this._boo = value && (''+value).toUpperCase();
  }
};

Now this is nice, but how can we use this approach for our subclass?

The deprecated, non-standard way

One possibility is to use the non-standard __proto__ property that allows us to change an objects prototype even after it has been created:

function Bar() {
}
Bar.prototype = {
  __proto__: Foo.prototype,
  get boo() {
    return 'Buh!';
  }
};

A standard based solution

Despite being deprecated the solution above is currently my favorite inheritance style. If you want to avoid using __proto__ for some reason you can write a helper function similar to Node’s util.inherits() that uses standard ECMAScript 5 features to achieve similar results:

function Foo() {
  // constructor code
}
Foo.prototype = {
  bar: function() {
    // do something
  }
};

function Bar() {
  // constructor code
}
util.prototype(Bar, Foo, {
  get boo() {
    return 'Buh!';
  }
});

Here is the implementation of the util.prototype function:

function prototype(ctor, superCtor, proto) {
  var props = {
    constructor: { value: ctor, writable: true, configurable: true }
  };
  Object.getOwnPropertyNames(proto).forEach(function(name) {
    props[name] = Object.getOwnPropertyDescriptor(proto, name);
  });
  ctor.prototype = Object.create(superCtor.prototype, props);
  ctor.super_ = superCtor;
}

TL;DR

The get/set operators are cool and __proto__ is your friend. If you don’t want to use it you can write a simple helper function to achive a similar result using standard ECMAScript features.

Spin.js

After writing a 138 bytes loading spinner I decided to create a fully featured version, suitable for real-world projects. The design goals were:

  • Consistent look & feel in all major browsers, including IE6.
  • No dependencies - No libraries, no images, no external CSS.
  • Small footprint - The script should be smaller than an animated GIF.

So here's the final result: spin.js

Screen_shot_2011-08-16_at_15

Animated loading spinner in 138 bytes

140bytes

Here's my contribution to the 140byt.es project: An animated loading spinner in 138 bytes [demo], [gist].

I did something similar last year, a cross-browser activity indicator that uses SVG and VML, but that's 4KB in size without the jQuery dependency. Since creating SVG or VML elements isn't that trivial, I decided to use another popular indicator shape: a circle of balls.

The trick is to use eight bullet characters •••••••• (unicode 2022) an arrange them in a cricle using an external stylesheet. By applying some additional CSS3 styles it possible to re-create the classic indicator look while using the circle of balls as fallback for older browsers.

See it in action

 

 

Finding memory leaks in Node.js applications

Thanks to Google's work on devtools and Danny Coates' node-inspector it's easy to browse and analyze heap snapshots in Node.js. Unfortunately one of the most useful features to find memory leaks is currently disabled: The possibility to see the graph of retainers, i.e. the the objects that prevent another object from being garbage collected.

Screen_shot_2011-04-06_at_14

Here is patched version of the v8-profiler module, that enables this feature and produces results as in the screenshot above.

 

JSHint TextMate Bundle

Update: The bundle now uses JSHint instead of JsLint.

Screenshot

Features:

  • Pretty UI
  • Runs automatically upon save (⌘S)
  • Can be bypassed by pressing ⇧⌘S
  • Output is only shown when errors are found
  • Window is automatically closed when it looses focus
  • Based on Node.js

Installation

Download the zip file and rename the extracted folder to jshint.tmbundle. Double-click.

Alternatively you can also install the it using GetBundles.

Prerequisites

You need Node.js and TextMate, that’s all.

Live form-validation with Node.js

In one of the last posts I showed you how to run same jQuery code on both client and server. In the example we used the validation plugin to check whether an email field contains a valid address. The check was first performed on the client and later, upon submit, once again in Node.js.

This time we take things one step further and add another server-side check. If JavaScript is enabled on the client, the validation plugin will perform an AJAX request and display an error message if the address is invalid (already taken).

Screenshot

In a real-world signup form we would perform a database lookup, but for this example we’ll just check if the address equals my own:

$('<input name="email" type="text" class="required email">').remote(
     function(value) {
         return value != 'fgnass@neteye.de';
     },
     'Address already taken.'
 );
 // Setup remote validation on the client-side
 $('head').append($('<script>', {src: '/js/validator.remote.js'}));

Remember, this code is executed on the server only. The client has no chance to see the implementation. For the complete example, please check out the demo-app that comes with jayno.

Form-validation with Jayno

In the last post I mentioned the jQuery Validation Plugin. This time I’ll show you how this plugin can be used with Jayno to validate forms on the client and on the server. Fist let’s see how one would use the validation plugin in the browser:

$('body').append(
    $('<form method="POST">').append(
        $('<input class="required email" name="email" type="text">'),
        $('<input type="submit">')
    ).validate()
);

Moving validation to the server

We can use exactly the same code in our Jayno view to perform server-side validation. We just have to put that code into a file called views/form.js and add the following route to our application:

app.get('/', function(req, res) {
    res.render('form.js');
});

Unfortunately nothing will happen though, since the validation plugin doesn’t do anything until the form is submitted. Besides that the server doesn’t know anything about the actual values yet, so lets fix that by handling POST requests:

app.post('/', function(req, res) {
    res.render('form.js', {
        onready: function($) {
            // Populate the form fields
            $.each(req.body, function(name, value) {
                $(':input[name=' + name + ']').val(value);
            });
            // Trigger submit-event to validate the form
            $('form').trigger('submit');
        }
    });
});

Again we use jQuery to find and populate the fields. Afterwards we trigger an submit-event to kick-off the validation.

Re-enable client-side validation

We successfully moved the whole validation process to the server. In order to perform it on both sides, client and server, all we need to do is to add .client('validate') to our view:

$('body').append(
    $('<form method="POST">').append(
        $('<input class="required email" name="email" type="text">'),
        $('<input type="submit">')
    ).validate().client('validate')
);

I’ll cover the Jayno client() plugin on one of the next posts and show you how to perform remote AJAX validations.