Moving to GitHub Pages
I'm moving this blog over to GitHub Pages. I'll redirect the feed URL so you don't have to do anything in order to stay subscribed. The first post on that new platform is about the platform itself and the reason for moving.
I'm moving this blog over to GitHub Pages. I'll redirect the feed URL so you don't have to do anything in order to stay subscribed. The first post on that new platform is about the platform itself and the reason for moving.
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 };
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 };
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.
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?
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!'; } };
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; }
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.
After writing a 138 bytes loading spinner I decided to create a fully featured version, suitable for real-world projects. The design goals were:
So here's the final result: spin.js
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.
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.
Here is patched version of the v8-profiler module, that enables this feature and produces results as in the screenshot above.
Update: The bundle now uses JSHint instead of JsLint.

Features:
Download the zip file and rename the
extracted folder to jshint.tmbundle. Double-click.
Alternatively you can also install the it using GetBundles.
You need Node.js and TextMate, that’s all.
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).

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.
I've created a TextMate theme to preview Markdown content using the original GitHub CSS.
To install the theme, download the archive and place the extracted folder in ~/Library/Application Support/TextMate/Themes/WebPreview - you can then select the GitHub theme from the drop-down:
The node.js supervisor is can now be installed via npm:
npm install node-dev
Since the dev script is no longer bundled with your app, the usage is slightly different now. Instead of node dev script.js you now type node-dev script.js.
For more information please visit the GitHub project page.
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() );
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.
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.