Node Roundup: Node 0.4, Stylus, Ringo 0.7
Welcome to the Node Roundup. Send in your apps and libraries using our contact form or @dailyjs.
Move Code to 0.3: Node 0.4 Coming Soon
In Move Code to v0.3 on the nodejs group, Ryan Dahl recently suggested that people move code to Node 0.3 as the next stable branch, 0.4, will be released in the next week. Exciting times!
Stylus

Stylus is yet another interesting product from LearnBoost and TJ Holowaychuk that aims to revolutionise CSS generation. It’s currently available through npm, and can be installed with npm install stylus.
The language dramatically cuts down the amount of syntax required by CSS, and is really what I thought LESS would be when I first heard about it.
Almost everything is optional, including property colons, and it supports conditionals, mixins, variables, interpolation, imports, iteration, nested selectors, and more. TJ has already made a screencast demonstrating the language: Stylus screencast. It’s definitely easy to see the evolution from Jade to Stylus, and I think they’ll be a joy to use together.
I also noticed TJ wrote inspect recently, which can iterate over objects and display a hierarchy of associated properties.
Ringo 0.7
I know this is the Node roundup, but sometimes I wonder if it would be better to name it the Server Side Roundup. Anyway, Ringo 0.7 has been released, with some interesting new changes:
fs-basehas been folded into thefsmodule- Script execution will continue until asynchronous ringo/scheduler and ringo/httpclient have finished
- Resources outside a repository root can now be
require’d using relative paths
There are a lot more changes in the 0.7 release notes on the Ringo Wiki.
jQuery Roundup: jQuery 1.5
jQuery 1.5
jQuery 1.5 has been released. The biggest changes are an Ajax rewrite, jQuery.sub, and traversal method performance improvements.
11 More Things I Learned from the jQuery Source

11 More Things I Learned from the jQuery Source by Paul Irish is a 29 minute screencast that covers:
- pseudo-module patterns with self-executing anonymous functions (apparently some people prefer the term IIFE)
data()’s new HTML5 features- Operator precedence
- Live and static nodelists
- cssHooks and other CSS stuff
- How
$.fnworks
If you follow our LMAF series you’ll know digging into jQuery is interesting, so I think you’ll enjoy this too.
jQuery Deconstructed

On a similar note, jQuery Deconstructed is an interesting visual tour of jQuery’s innards:
The Deconstructed series is designed to visually and interactively deconstruct the internal code of JavaScript libraries, including jQuery, Prototype and MooTools. It breaks the physical JavaScript into visual blocks that you can easiliy navigate. Each block opens to reveal its internal code. Clickable hyperlinks allow you to follow program flow.
Node Tutorial Part 11
Welcome to part 11 of Let’s Make a Web App, a tutorial series about building a web app with Node. This series will walk you through the major areas you’ll need to face when building your own applications. These tutorials are tagged with lmawa.
Previous tutorials:
- Part 1: Introduction
- Part 2: Installation and Skeleton App, source code commit: 4ea936b
- Part 3: RESTful Methods and Testing, source code commit: 39e66cb
- Part 4: Templates, Partials, Creating and Editing Documents, source code commit: f66fdb
- Part 5: Authentication, Sessions, Access Control Middleware, source code commit: 03fe9b
- Part 6: Interface Basics, source code commit: f2261c
- Part 7: Node Library Versions, Jade Tricks, Error Pages, source code commit: 929f5
- Part 8: Flash Messages and Helpers, source code commit: 841a49
- Part 9: Remember Me, source code commit: 1904c
- Part 10: Markdown, source code commit: 11d33
Checking Out Each Commit
You might have noticed I include a fragment of the SHA1 of each source code commit, so each part of the tutorial can be downloaded. A reader got in touch with us to ask how to actually do this. It’s this simple:
git clone git://github.com/alexyoung/nodepad.git
git checkout -b tutorial_8 841a49
This will create a new local branch with the commit at 841a49. The part that says -b tutorial_8 just gives the branch a name, so you could check out each commit (or any that you’re interested in) and easily switch between them.
Bugs and Improvements
Over the weekend, Matthias Lübken helped me figure out some odd behaviour in Nodepad. We had quite a lengthy discussion through GitHub and Twitter, and found that Nodepad doesn’t run too well on Node 0.3.x, so I recommend using 0.2.4 if possible.
On DailyJS we recently featured n which is a Node version manager — you could use it to switch between 0.2.4 and the 0.3 series. Another tool that can do this is nvm.
In addition, Matthias found that Jade’s latest version had a slight change in behaviour that caused Nodepad’s templates to generate escaped HTML from flash messages by mistake, so that’s now fixed as well.
Matthias also suggested that the app should use a session secret for added security. You should use the secret option for express.session for added security if possible.
Tests with Expresso and Zombie.js
The original basic tests I wrote no-longer work, which is partially my fault and partially due to a lack of good resources on testing with Expresso. Like most of our readers, I’m comfortable with server-side JavaScript and client-side tools, which made me wonder if it would be easier to write tests in a style that reflects that. Therefore, I decided to combine Expresso with Zombie.js.
So I went on a quest to write idiomatic Node test code with Expresso, Zombie.js, and Mongoose. The initial skeleton I created looks like this:
// Force test environment
process.env.NODE_ENV = 'test';
var app = require('../app'),
path = require('path'),
fs = require('fs'),
assert = require('assert'),
zombie = require('zombie'),
events = require('events'),
testRunner = require('./runner'),
models;
// Mongoose models defined in the app -- I actually export them as app.User, etc.
models = ['User'];
function removeTestData(models, next) {
// Clear test data
}
(function() {
// The app needs to run for Zombie to test it
app.listen(3001);
// Clear tests on each run
removeTestData(models, function() {
// Fixtures
var user = new app.User({'email' : 'alex@example.com', 'password' : 'test' });
user.save(start);
});
})();
function teardown() {
removeTestData(models, function() {
process.exit();
});
}
function start() {
exports['test login'] = function() {
// The Zombie code goes here
};
}
A self-executing anonymous function starts everything off. It runs the app on a different port to the development app, clears the test data, then creates a user. This is asynchronous, so if we had more fixtures, the very last save should call the start() function. Expresso will wait around for tests to be exported, so this allows us to use Mongoose’s asynchronous API and run tests when we’re ready.
If you understand that then take a look at the full test code:
// Force test environment
process.env.NODE_ENV = 'test';
var app = require('../app'),
path = require('path'),
fs = require('fs'),
assert = require('assert'),
zombie = require('zombie'),
events = require('events'),
testRunner = require('./runner'),
models;
models = ['User'];
function removeTestData(models, next) {
var modelCount = models.length;
models.forEach(function(modelName) {
modelCount--;
app[modelName].find().all(function(records) {
var count = records.length;
records.forEach(function(result) {
result.remove();
count--;
});
if (count === 0 && modelCount === 0) next();
});
});
}
(function() {
// The app needs to run for Zombie to test it
app.listen(3001);
// Clear tests on each run
removeTestData(models, function() {
// Fixtures
var user = new app.User({'email' : 'alex@example.com', 'password' : 'test' });
user.save(start);
});
})();
function teardown() {
removeTestData(models, function() {
process.exit();
});
}
function start() {
exports['test login'] = function() {
zombie.visit('http://localhost:3001/', function(err, browser, status) {
// Fill email, password and submit form
browser.
fill('user[email]', 'alex@example.com').
fill('user[password]', 'test').
pressButton('Log In', function(err, browser, status) {
// Form submitted, new page loaded.
assert.equal(browser.text('#header a.destroy'), 'Log Out');
teardown();
});
});
};
}
The Zombie.js code visits the URL (notice it’s port 3001), then uses the browser object to fill out the login form, submit it, then use a standard assert.equal assertion to compare the text node to the string 'Log Out'.
Making it Generic
If we want to separate Nodepad’s tests into multiple files, repeating all of that Mongo fixture code would be poor form, so I’ve tried to make it more generic. This is my test/helper.js file:
// Force test environment
process.env.NODE_ENV = 'test';
var state = {
models: []
};
function prepare(models, next) {
var modelCount = models.length;
models.forEach(function(model) {
modelCount--;
model.find().all(function(records) {
var count = records.length;
records.forEach(function(result) {
result.remove();
count--;
});
if (count === 0 && modelCount === 0) next();
});
});
};
module.exports = {
run: function(e) {
for (var test in state.tests) {
e[test] = state.tests[test];
}
},
setup: function(next) {
prepare(state.models, next);
},
end: function() {
prepare(state.models, process.exit);
},
set models(models) {
state.models = models;
},
set tests(tests) {
state.tests = tests;
}
};
The environment is set to test because my default Nodepad settings have a test database defined which means it should be safe to trash data each time a set of tests is run. The prepare function just loops through each Mongoose model and removes associated data (this is reused from the previous example).
Now the tests are a little bit more concise:
var app = require('../app'),
assert = require('assert'),
zombie = require('zombie'),
events = require('events'),
testHelper = require('./helper');
app.listen(3001);
testHelper.models = [app.User];
testHelper.setup(function() {
// Fixtures
var user = new app.User({'email' : 'alex@example.com', 'password' : 'test' });
user.save(testHelper.run(exports));
});
testHelper.tests = {
'test login': function() {
zombie.visit('http://localhost:3001/', function(err, browser, status) {
// Fill email, password and submit form
browser.
fill('user[email]', 'alex@example.com').
fill('user[password]', 'test').
pressButton('Log In', function(err, browser, status) {
// Form submitted, new page loaded.
assert.equal(browser.text('#header a.destroy'), 'Log Out');
testHelper.end();
});
});
}
};
Did you notice I used a setter for setting tests and models? I thought that was an interesting trick so I left it in there.
Conclusion
When writing Expresso tests it’s important to remember that it’s possible to delay the running of tests by deferring setting them in module.exports. TJ’s example in the Expresso documentation uses setTimeout, but keeping a callback floating also works.
If you run my code (remember to use expresso), you should see this:
alex@mog ~/Code/nodepad[git:master]$ expresso test/app.test.js
GET / 2 ms
GET /sessions/new 10 ms
GET /javascripts/application.js 1 ms
GET /javascripts/json.js 1 ms
POST /sessions 2 ms
GET /documents 8 ms
GET /javascripts/application.js 1 ms
GET /javascripts/json.js 1 ms
GET /documents/4d21d96f2410f20000000037.json 5 ms
100% 1 tests
Zombie.js (or Tobi) is a very JavaScript developer friendly way to test, but you still need some kind of test runner. A lot of people are using Vows, and I’m sure nodeunit would work well too.
I found it disappointing that there aren’t many open source Express apps with solid tests. Also, writing tests without a convenient way of handling setup, teardown, and fixtures seems awkward to me.
You should now be able to at least run the Nodepad tests. Hopefully next week I’ll be able to write more detailed Zombie.js tests so we can really push what we’ve created so far.
This version is commit 6a269ce.
References
PhantomJS, load.js, Phantom Limb, OpenOdyssey
PhantomJS
PhantomJS by Ariya Hidayat is a WebKit-based JavaScript tool for exploiting the power of WebKit. Let’s say you want to generate a PNG from an SVG file:
if (phantom.state.length === 0) {
if (phantom.args.length !== 2) {
console.log('Usage: rasterize.js URL filename');
phantom.exit();
} else {
var address = phantom.args[0];
phantom.state = 'rasterize';
phantom.viewportSize = { width: 600, height: 600 };
phantom.open(address);
}
} else {
var output = phantom.args[1];
phantom.sleep(200);
phantom.render(output);
phantom.exit();
}
This will produce a PNG when run through phantomjs on the command line:
phantomjs rasterize.js http://ariya.github.com/svg/tiger.svg tiger.png
This example is from the PhantomJS QuickStart.
What really interests me about this project is generating nice PDFs from HTML. WebKit has been ported to quite a few platforms, and PhantomJS should run on Linux, Windows, and Mac OS X, so it could be a great tool to have on your server.
load.js
load.js by Chris O’Hara is a small lazy-loading and dependency management library:
load('jquery.js').then('jquery-ui.js', 'jquery-ui-theme.js')
.then('myscript.js')
.thenRun(function () {
alert('Loaded.');
});
load('underscore.js');
I like the chained API, which just so happens to be created with chain.js by the same author.
Phantom Limb
Phantom Limb by Brian Carstensen makes desktop browsers to simulate touchscreen device events:
A
mousedownfires atouchstart. Amousemovefires atouchmoveif the mouse is down, and amouseupfires atouchend. These custom events are also assigned atouchesarray containing a reference to the event, just like a real touch event in a mobile browser.
Brian pointed out that this makes debugging mobile apps easier, because you’re not limited to Mobile Safari’s limited debugging tools. There’s also a bookmarklet for activating Phantom Limb, which means you could use it on any page.
WebGL Model Viewer

Christopher Chedeau sent us a link to jDataView, a library for reading binary files in browsers. His blog post, Javascript – jDataView: Read Binary File includes some background on the project and a great demo: a World of Warcraft Model Viewer. You’ll need a WebGL-enabled browser to view this demo.
Dealing with binary data is inherent to games development, so it’s worth taking a look at jDataView if you’re working in that area.
OpenOdyssey

OpenOdyssey by Michal Budzynski for the Mozilla GameOn Competition is a simple browser-based game that uses the Mibbu game framework. The basic gameplay mechanics are fairly solid, so it’ll be interesting to see what Mibbu is like when Michal releases it.
Let's Make a Framework: Project Websites
Welcome to part 48 of Let’s Make a Framework, the ongoing series about building a JavaScript framework.
If you haven’t been following along, these articles are tagged with lmaf. The project we’re creating is called Turing.
Hosting Documentation
GitHub will host open source projects for free. It renders README files on the project’s page, and works with textile, markdown, and probably more formats. Most open source projects I encounter include a nicely formatted README with code examples.
But GitHub allows us to go beyond that with the GitHub pages feature. This can be used to host the documentation we generated with dox last week at http://username.github.com/project-name. In this case it’s at alexyoung.github.com/turing.js/.
GitHub’s documentation on Pages is actually very good, but I’ll walk through how I set up Turing’s documentation here as well. Pages will look for a gh-pages branch in your project. It would be possible to fork the entire project, but I created a clean branch:
git symbolic-ref HEAD refs/heads/gh-pages
rm .git/index
git clean -fdx
Then I added a quick Jakefile that downloads Turing’s latest documentation from GitHub:
var exec = require('child_process').exec;
desc('Updates the documentation from GitHub');
task('docs', [], function() {
exec('curl -O https://github.com/alexyoung/turing.js/raw/master/docs/index.html');
});
Your projects might require totally unique hand-written documentation — in which case use a clean branch — or you might have a copy of your main branch and just generate an index.html file (many projects work this way).
Next I pushed the branch to GitHub:
jake docs
git add .
gc -m 'Created gh-pages branch with documentation and a Jake task to fetch the documentation from GitHub'
git push origin gh-pages
# Switch back to master
git checkout master
GitHub then sent me a notice to say the documentation was generated.
These branches can be viewed on GitHub:

Registering a Domain Name
Another nice GitHub Pages feature is custom domains. I registered turingjs.com and set up a CNAME file in Turing’s gh-pages branch. The CNAME file just contains turingjs.com, then I set up a record pointing the domain to 207.97.227.245 — this is an IP address at GitHub.
I bought this domain and configured the DNS through NearlyFreeSpeech.NET, a company recommended to me by a friend. They have a fairly unique pricing policy which seems appropriate for an open source project, so check them out if you’d like a domain or some hosting for your own work.
A Simple Project Site
I’ve adapted the documentation generated by dox to include some introductory text with code examples. In general when writing your own sites and READMEs, consider including the following:
- A link to the source code
- Code examples
- A link to documentation
- License information
- Installation advice
- Planned updates
- Contribution guidelines
- Social links: Twitter, Facebook, Google Groups, email, etc.
This will make it easier for people to use your project and contribute. It also makes it easier for journalists who want to write about your project.
I’ve started including a list of recent updates in some of my open source projects. Technically this information can be obtained from the version control system, but it’s sometimes useful to draw attention to certain updates.
References
Node Roundup: Express Form, streamline.js, long-stack-traces
Welcome to the Node Roundup. Send in your apps and libraries using our contact form or @dailyjs.
Express Form
Express Form by Dan Dean is a middleware data filtering and validation library for Express. It looks like this:
app.post(
// Route
'/user',
// Form filter and validation middleware
form(
filter("username").trim(),
validate("username").required().is(/^[a-z]+$/),
filter("password").trim(),
validate("password").required().is(/^[0-9]+$/)
),
// Express request-handler now receives filtered and validated data
function(req, res){
if (!req.form.isValid) {
// Handle errors
console.log(req.form.errors);
} else {
// Or, use filtered form data from the form object:
console.log("Username:", req.form.username);
console.log("Password:", req.form.password);
}
}
);
The form method is the middleware which will add req.form.errors and req.form.isValid. I haven’t actually used this yet but validation at the middleware layer is very intriguing.
streamline.js
streamline.js released by Sage is a kind of pre-processing library for Node that makes asynchronous code look synchronous.
The example given in the documentation of asynchronous API usage is asynchronous Node file system code (which could of course be written with the synchronous methods anyway):
function fileLength(path, callback) {
fs.stat(path, function(err, stat) {
if (err) { callback(err); return; }
if (stat.isFile()) {
fs.readFile(path, function(err, data) {
if (err) { callback(err); return; }
callback(null, data.length);
});
} else {
callback(new Error(path + " is not a file"));
}
});
}
The streamline.js version uses the underscore symbol as a plug for values that will be available later, so the previous example could be written like this:
function fileLength(_, path) {
if (fs.stat(path, _).isFile())
return fs.readFile(path, _).length;
else
throw new Error(path + " is not a file");
}
If you’re lost in callbacks and find promises and futures unsatisfactory you might want to try this library. It’s got a lot of examples and more features for parallelizing streamlined code.
long-stack-traces
long-stack-traces by Tom Robinson uses the V8 stack track API to generate long stack traces in Node or a Chromium-based browser. It’s available through npm as long-stack-traces.
Just loading the library will make it work in Node, so this long-stack-trace example will produce:
Uncaught Error: readFile
at Timer.secondTimeout (/Users/alex/example.js:6:15)
at node.js:772:9
----------------------------------------
at Object.setTimeout
at initSecondTimeout (/Users/alex/example.js:5:5)
at /Users/alex/example.js:23:7
at fs:82:13
at node.js:772:9
Rather than:
/Users/alex/example.js:5
throw new Error(tag);
^
Error: readFile
at Timer.secondTimeout [as callback] (/Users/alex/example.js:5:15)
at node.js:772:9
jQuery Roundup: jQuery UI 1.8.9, Zepto 0.4, Toast Message
Welcome to the jQuery roundup. You can send your plugins and articles in for review through our contact form or @dailyjs.
jQuery UI 1.8.9
jQuery UI 1.8.9 has been released. This is a maintenance release that includes bug fixes and localisations, see the 1.8.9 changelog for more.
Zepto 0.4
Zepto 0.4 was released a few days ago, which introduces JSONP and improved iterators. I also noticed Thomas Fuchs has made Zepto a lot more jQuery compatible. The Zepto GitHub repository has detailed examples and there’s a website now too at zeptojs.com.
Thomas wrote a post about it here: Zepto.js v0.4 – JSONP & more DOM goodness.
I wrote about Zepto last year in A Look Inside Zepto.js.
jquery-toastmessage-plugin

jquery-toastmessage-plugin (Apache License 2.0) by Daniel Bremer-Tonn at akquinet A.G is another handy little Growl-style messaging system. The Toast demo shows various message types in action.
I tried forcing it to display lots of messages and it handles that situation fairly well — the messages appear as others fade, rather than causing a scrollbar to appear. This seems like something that would work well in a Backbone.js/jQuery UI app.
Node Tutorial Part 10
Welcome to part 10 of Let’s Make a Web App, a tutorial series about building a web app with Node. This series will walk you through the major areas you’ll need to face when building your own applications. These tutorials are tagged with lmawa.
Previous tutorials:
- Part 1: Introduction
- Part 2: Installation and Skeleton App, source code commit: 4ea936b
- Part 3: RESTful Methods and Testing, source code commit: 39e66cb
- Part 4: Templates, Partials, Creating and Editing Documents, source code commit: f66fdb
- Part 5: Authentication, Sessions, Access Control Middleware, source code commit: 03fe9b
- Part 6: Interface Basics, source code commit: f2261c
- Part 7: Node Library Versions, Jade Tricks, Error Pages, source code commit: 929f5
- Part 8: Flash Messages and Helpers, source code commit: 841a49
- Part 9: Remember Me, source code commit: 1904c
Markdown
It would be nice if our notepad app allowed some form of markup. There are a few markdown libraries available through npm, but markdown seems to be quite popular.
Install it like this:
npm install markdown
It’s easy to use:
var markdown = require('markdown').markdown;
markdown.toHTML('# Welcome\n\nThis is markdown');
// => '<h1>Welcome</h1>\n\n<p>This is markdown</p>'
I updated Nodepad’s dependencies to include this in the package.json file:
// ...
"dependencies": {
"express": "1.0.0",
"mongoose": "0.0.4",
"connect-mongodb": "0.1.1",
"jade": "0.6.0",
"markdown": "0.2.0"
}
Then near the top of app.js I added the require:
var express = require('express@1.0.0'),
app = module.exports = express.createServer(),
mongoose = require('mongoose@0.0.4').Mongoose,
mongoStore = require('connect-mongodb@0.1.1'),
markdown = require('markdown').markdown,
// ...
I’ve added a html format option for GET /documents/:id.html which contains the markdown renderer:
// Read document
app.get('/documents/:id.:format?', loadUser, function(req, res, next) {
Document.findById(req.params.id, function(d) {
if (!d) return next(new NotFound('Document not found'));
switch (req.params.format) {
case 'json':
res.send(d.__doc);
break;
case 'html':
res.send(markdown.toHTML(d.data));
break;
default:
res.render('documents/show.jade', {
locals: { d: d, currentUser: req.currentUser }
});
}
});
});
Visiting a valid document ID with ‘.html’ will now render HTML using markdown. This is easy to access using a quick $.get call. I’ve added another link next to the Save button (#html-button) which toggles the rendered markdown view in a div:
$('#html-button').click(function() {
var container = $('#html-container');
if (container.is(':visible')) {
container.html('').hide();
$('#html-button').removeClass('active');
} else {
$('#save-button').click();
$('#html-button').addClass('active');
var id = $('#document-list .selected').itemID();
$.get('/documents/' + id + '.html', function(data) {
// Saved, will return JSON
container.html(data).show();
});
}
});
This uses jQuery’s is() to detect if the markdown container is visible, and adds a class name to the button which can be styled to indicate that the markdown display can be toggled. It looks like this:

Delete Button
The layout has changed since early on in this series, so I’ve changed the delete code to work with the new layout. It just uses the same jQuery with an updated URL for the $.post.
Conclusion
Adding markdown or textile support to Node apps is pretty easy now there are a few easily installable modules through npm. If you want to check the commit for this part of the project, it’s available at 11d33e1.
getImageData, janky.post, dox
$.getImageData

$.getImageData by Max Novakovic provides pixel level access to images from any domain. It uses a server-side component with JSONP requests that base64 encodes the images and returns them to the client for further Canvas processing.
There are PHP, Python, and Node examples in the getImageData/server-examples directory
Max told me that David Desandro has written a plugin based on this project called Close Pixelate (which we’ve featured previously on DailyJS).
janky.post
janky.post by Thomas Rampelberg is a library that aims to get around cross-domain request limitations, as well as JSONP limitations. For example:
janky({ url: "http://example.com:8080/api",
data: { foo: 'bar', baz: [1,2,3] },
success: function(resp) {
console.log('server responded with: ' + resp);
},
error: function() {
console.log('error =(');
}
});
That example basically replicates a JSONP result (but you’ll notice that there’s actually errors that occur, no firing requests into the ether)
There’s a janky.post demo and janky.post documentation. There are currently Tornado and Google App Engine servers.
Dox Updates
TJ Holowaychuk updated dox to 0.0.4, which includes a few fixes and a small patch I put in there so an introduction markdown file can be included instead of using the --desc option.
I think dox is a cool little project, so I encourage you to try it out and submit your own tweaks and improvements. GitHub makes open source collaboration easy (fork, clone, push, pull request), so you’ve got no excuses not to help out!
Let's Make a Framework: JSDoc
Welcome to part 47 of Let’s Make a Framework, the ongoing series about building a JavaScript framework.
If you haven’t been following along, these articles are tagged with lmaf. The project we’re creating is called Turing.
JSDoc
Last week I reviewed various approaches to JavaScript documentation, and I decided to use dox. Dox can be installed with npm:
npm install dox
By the end of this tutorial, you’ll be able to make something like this:

Although dox produces readable documentation — which is incidentally perfect for writing tutorials because the code is inline — it can’t parse everything JSDoc offers. It’s a simple tool designed to suit the author’s requirements, but I like it and would like to see it grow in the future.
Despite not supporting everything outlined by jsdoc-toolkit, I’m going to use dox and write JSDoc comments as if it fully supports them.
JSDoc Comment Structure
Each file in your project should contain author, copyright, and license details. For example:
/*!
* Turing - Module Name
* Copyright (C) 2010-2011 Alex R. Young
* MIT Licensed
*/
/**
* A private namespace to set things up against the global object.
*/
(function(global) {
I like to write comments in a relatively informal conversational style, as full sentences. I might be extra-verbose because this is a tutorial, so you can be a bit more succinct in your own projects.
Where JSDoc comments come in handy is outlining the intended inputs and outputs of a function:
/**
* Determine if an object is an `Array`.
*
* @param {Object} object An object that may or may not be an array
* @returns {Boolean} True if the parameter is an array
*/
turing.isArray = Array.isArray || function(object) {
return !!(object && object.concat
&& object.unshift && !object.callee);
};
Notice I’ve used backticks around the Array keyword. Dox has markdown support, so this will be converted into a code tags in the resulting HTML.
The @param and @returns directives are known as tags. The jsdoc-toolkit wiki lists lots of tags. The @param tag actually has quite a few ways of defining method parameters, including support for optional parameters.
Long Examples
Because dox supports markdown, long code examples can be included simply through indentation:
/**
* Chain animation module calls, for example:
*
* turing.anim.chain(element)
* .highlight()
* .pause(250)
* .move(100, { x: '100px', y: '100px', easing: 'ease-in-out' })
* .animate(250, { width: '1000px' })
* .fadeOut(250)
* .pause(250)
* .fadeIn(250)
* .animate(250, { width: '20px' });
*
* @param {Object} element A DOM element
* @returns {Chainer} Chained API object
*/
anim.chain = function(element) {
return new Chainer(element);
};
Generating the Documentation
Dox can be run with just dox file.js, and it’ll output the HTML to the console. The HTML is totally self-contained, which means there are no extra image, CSS, or JavaScript files. This will generate the documentation for turing.core.js:
dox --title Turing turing.core.js > index.html
I also added this to the project’s Jakefile (node-jake):
var exec = require('child_process').exec;
desc('Documentation');
task('docs', [], function() {
exec('dox --title Turing *.js > docs/index.html');
});
Build Systems
The build system is closely tied to project management tasks like generating documentation. Generating documentation should be consistent and easy to run so it doesn’t get forgotten as the project changes over time, therefore adding a docs task is a good idea.
Every time I go over TJ Holowaychuk’s projects (and jQuery) I’m reminded that GNU make was more than enough for our needs. Build system choice is partially dependent on how much JavaScript from Node, Narwhal, Rhino, etc. you want to reuse in your build system — Python, Java, and Ruby projects often use native build systems to get access to native libraries. Also, you already know how to write JavaScript pretty well but might not be familiar with make.
However, when writing your own projects make is more likely to be on a system than node-jake, and it could always invoke JavaScript scripts anyway. I recommend giving it a look before deciding on the build system for your own projects.
Side note: I’ve removed the Narwhal support from the Jakefile to focus on using Node for the build system instead. The main motivation for this was to get some cross-pollination between the Node tutorial series and this series.
References
Node Roundup: Node 0.3.5, express-on-railway, drty, NodeFu, maptail, Minotaur
Welcome to the Node Roundup. Send in your apps and libraries using our contact form or @dailyjs.
Please prepare yourself for a rapid-fire burst of Node news.
Node 0.3.5 Released
Node 0.3.5 has been released. The documentation is available at docs/v0.3.5/api and the source is here: node-v0.3.5.tar.gz.
See the announcement for the full list of updates.
express-on-railway
express-on-railway brings Rails-like features to Express. There’s a command line tool, railway, for creating new projects with a very familiar layout. RESTful routes can be easily set up, and there’s a neat little model system based on Redis.
It seems like an ambitious project, and if you’re familiar with the style of Rails it should be pretty easy to pick up.
drty
drty is a Django port for Node. It currently works with MySQL, and has routing, middleware, views, models, sessions, and Django templating support. There’s a blog example in the example directory.
I saw drty mentioned on Ryan Dahl’s Twitter account: @ryah: This looks awesome…
NodeFu
I’ve been looking at NodeFu, a Node-oriented hosting platform. It’s npm-friendly and deploys with git (like Heroku and Joyent’s Node SmartMachines). It’s currently free to try out, just follow the instructions on the site: NodeFu REST API.
We do not currently have a full featured website as we are focusing on the API and the service. We are currently running Node v.0.3.5 and updating all NPM modules on a weekly basis. Git is required to push your updates to Nodefu. All we ask is that you be a good steward of our service and community.
maptail

maptail by George Stagas is a Node app that can plot IP address accesses on a map. There’s a demo at live.stagas.com. It has cool graphics, which is of course why I featured it, but it also seems to be handling Hacker News traffic very well.
Minotaur
Minotaur (MIT X11 License) by Tomi is a long poll server that uses JSONP for communication. It comes with a simple chat client/server example app. The Node dependencies are fairly minimal: node-uuid, and cookie-node. The client-side uses jQuery and jquery-jsonp.
If you’re interested in seeing how the client might poll, take a look at minitaur.js. The author has written a post about the project here: Tales of the minotaur or long polling with node.js.
jQuery Roundup: jQuery 1.5, BigText, View, jKey, Jail
Welcome to the jQuery roundup. You can send your plugins and articles in for review through our contact form or @dailyjs.
jQuery 1.5 Beta 1
jQuery 1.5 Beta 1 has been released. The changes mainly centre around the Ajax module because it has been rewritten, but I also thought jQuery.subclass was worth mentioning.
BigText

BigText (GitHub: zachleat / BigText) by Zach Leatherman calculates the font size and word spacing required to fit text to a given width. It’s easier to understand the features by checking out the BigText demo.
It works like this:
For each line, it increments first by 16em until it detects a line break, backs off an interval then increments by 8em. It continues with 4em, 2em, 1em, 0.1em, until it finds the correct font-size to the nearest hundredth of an em.
jQuery View
jQuery View (GitHub: syntacticx / viewjs, MIT and GPL) by Ryan Johnson is a class and inheritance plugin for templates. This can result in some interesting opportunities for code reuse when combined with something like Backbone.js: the Backbone to-do app example by Jérôme Gravel-Niquet has been ported as a jQuery View demo with annotated source.
The View guide is probably the best way to get started with the library.
jKey
jKey by Oscar Godson makes keyboard shortcut handling much easier, for example:
$(window).jkey('alt+d', function() {
// Callback
});
$(window).jkey('w, up',function() {
// w OR up
});
There’s an interactive example in the jKey documentation.
Jail
Jail (GitHub: sebarmeli / JAIL, MIT) by Sebastiano Armeli-Battana is an asynchronous image loader:
Selected images will be downloaded after the document is ready not blocking the page to render elements in your page. Images can be loaded after an event is triggered (like clicking on a link, mouseovering on some elements, scrolling up/down) or after some delay.
The author’s recommendation is to use an img tag with small images in combination with a noscript tag like this:
<img class="lazy" src="/img/blank.gif" name="/img/image1.jpg">
<noscript>
<img src="/img/image1.jpg">
<noscript>
This approach can be seen in the Jail demos.
I’m not sure if using the name attribute this way constitutes an unacceptable abuse to enthusiastic spec zealots, but the plugin source is readable so it could be modified to suit other requirements.
Gestures, Scopeleaks, Wink, JLS, JavaScript Blogs
The Node tutorials will continue next week, in the meantime I have a backlog of news from our Twitter friends to catch up with.
Gestures

When I was writing gesture event support for the Let’s Make a Framework series, quite a few readers got in touch to say gesture recognition had been a sticking point for them during development of web-based iOS or Android apps. Tait Brown, who made my favourite jQuery UI theme Aristo, has now made Gestures which is a proof-of-concept library for gesture recognition.
The Gesture demo shows how the library works — gestures are recognised as shapes. At the moment this is based on the $1 Unistroke Recognizer in JavaScript.
I’m hoping Tait can add a simple multitouch API and release Gestures as a library soon.
scopeleaks.js
scopeleaks.js by Rui Lopes is a browser and CommonJS module for detecting global variable leaks. Once loaded with a script tag or through a require, the global variable state can be recorded and analysed:
var snapshot = scopeleaks.snapshot();
scopeleaks.leaks(snapshot);
It’s a simple library but might be useful for giving scripts a once-over before release.
A similar project is detect-global by Juriy Zaytsev (kangax).
Wink 1.2.3
Jérôme Giraud sent me a note that Wink 1.2.3 has been released, which adds support for Android (2.2, 2.3) devices. Jérôme wrote a Wink tutorial for DailyJS back in September.
JavaLikeScript
JavaLikeScript, or jls, is an interesting framework based on Prototype that runs on NSPR and SpiderMonkey for Windows and Linux. It includes a GUI library, CommonJS modules, file system access, a unit testing framework, and a network library.
The author hasn’t yet released the native source code yet, but it looks like he’s just preparing the build chain and documentation before releasing it. The API documentation gives an overview of the APIs if you’d like to dig a little deeper.
ecmazing JavaScript Blogs

Šime Vidas wrote in to let us know about ecmazing JavaScript Blogs, a JavaScript blog viewer. It feels very fast and makes it easy to quickly switch between blogs. Of course, most of those blogs are in my news reader, but I thought the fact it’s all client-side might interest readers who are front-end developers.
Arbor, Mug, I, Ristretto
Arbor

Arbor (GitHub: samizdatco / arbor) by Christian Swinehart is a graph visualisation library that uses jQuery and web workers. It provides a layout algorithm and graph organisation for building things like this: Atlas demo.
Arbor has a particle system which manages the state of the simulation:
sys = arbor.ParticleSystem();
node = sys.addNode('mynode', { mass:2, myColor:'goldenrod' });
Arbor’s API seems pretty easy to learn, so if you’d like to present data in a novel way or create some kind of simulation it’s worth checking out.
Mug
Mug (GitHub: timcameronryan / mug) by Tim Cameron Ryan is a JavaScript compiler for the JVM. The benefits according to the author are:
- Mug is faster than Rhino, favoring static compilation rather than a runtime interpreter.
- Minimal overhead. Standard library mug-js.jar is ~150kb.
- Mug’s goal is that compiled code be as similar to Java as possible, and easily debuggable.
- Mug uses CommonJS modules as its compilation units, allowing your code to be shared between Mug, node.js, RingoJS, and other implementations.
He also says the Mug compiler is written in Clojure, a language which I enjoy getting time to use. Take a look at compiler.clj if you’re interested in what that might look like.
Emphasis
Michael Donohoe at the New York Times has released their open source Emphasis library (GitHub: NYTimes / Emphasis). This library makes it possible to “deep link” to specific article text — double tapping the shift key displays paragraph icons which can be clicked to highlight a paragraph. Selecting a paragraph or a sentence within it updates the URL hash with parameters that can be used to share the highlight.
This library requires Prototype. To see more open source code from New York Times, take a look at the New York Times GitHub account.
I
I by Rob Robbins is a dependency manager with defer and async support. The name leads to some memorable API method names: I.amDefined, I.require, etc.
The library comes with some Ruby tools to read source and generate dependency files.
Ristretto
Ristretto by Adrien Friggeri is another dependency management tool with concatenation which can be installed with npm. It can be used with JavaScript or Coffee. What made this interesting to me is it allows developers to use CommonJS modules and then write out a browser-friendly file.
If you’ve been following our Let’s Make a Framework Series you’ll know I made a simplified CommonJS module-based testing system, but getting modules to behave in a browser was tricky to say the least. Adding support for CommonJS modules to Ristretto seems like a smart move.
Let's Make a Framework: Writing Documentation
Welcome to part 46 of Let’s Make a Framework, the ongoing series about building a JavaScript framework.
If you haven’t been following along, these articles are tagged with lmaf. The project we’re creating is called Turing.
Over the next few parts I’m going to discuss writing documentation for JavaScript projects. If you’re writing open source code documentation isn’t just a polite addition to a project, it goes a long way to helping your project take off. A well-written README helps, but full-on API documentation makes projects look professional. Even if your project is closed-source, documentation will help new colleagues get on board more quickly, or help you remember how things work for long-running projects.
Let’s take a look at the popular JavaScript frameworks to see how they manage their documentation.
jQuery

jQuery’s documentation is hosted on docs.jquery.com, which is a wiki with searchable documentation for the entire API. Each major API area is listed in the navigation, and each page has a list of the methods for that area. The pages contain example code and comments through Disqus.
The source code comments are mainly concerned with notes about specific bugs or unusual bits of code that need explanation.
Prototype
Prototype’s documentation, available at api.prototypejs.org, is generated by pdoc. PDoc is:
… an inline comment parser and JavaScript documentation generator written in Ruby. It is designed for documenting Prototype and Prototype-based libraries.
Prototype uses comments written in markdown that can be generated into documentation using pdoc. Take a look at src/prototype/ajax.js to see an example.
/**
* == Ajax ==
*
* Prototype's APIs around the `XmlHttpRequest` object.
*
* The Prototype framework enables you to deal with Ajax calls in a manner that
* is both easy and compatible with all modern browsers.
*
* Actual requests are made by creating instances of [[Ajax.Request]].
In contrast to jQuery, the documentation is inside the framework’s source itself.
JSDoc
JSDoc is actually a way to write inline API documentation. Comments can be annotated with @ signs to represent key metadata:
/**
* Example constructor.
*
* @constructor
* @this {Example}
*/
Full HTML documentation can be generated using jsdoc-toolkit. I’ve noticed that JavaScript projects are also using a project called dox with JSDoc-formatted comments.
Docco

Docco by Jeremy Ashkenas is an MIT licensed documentation generator that generates html files with inline code based on comments, with the original source next to them. It looks like this: jashkenas.github.com/docco. It’s installable from npm with npm install docco.
It’s a simple library that’s easy to use if you’re already using Node — which we’re using for Turing’s build system. If you want to try it out on Turing, install docco then run this from Turing’s directory: docco *.js.
Because Docco presents the original source code alongside comments it’s actually quite unique. In contrast, JSDoc will generate something that looks like Prototype or jQuery’s documentation. I’ve noticed many simple Node libraries are using Docco lately.
Ronn
Ronn by Ryan Tomayko and ronnjs can be used to generate documentation from sets of files. With ronnjs, you’re limited to markdown files. The results can be man pages or HTML. The name is a pun on roff.
GitHub Wikis
GitHub projects get a wiki that’s actually powered by Git itself. It’s possible to write them in textile, and there’s a detailed blog post on the GitHub blog: Git-backed Wikis. This is a great tool for projects that need documentation outside of the API, like FAQs, installation guidelines, and example code.
GitHub also has GitHub Pages, which can be used to host static files at you.github.com. Pages could be used to host the documentation generated by a tool like Docco or dox.
Conclusion
I’d imagine that many of you are interested in learning some JSDoc, so let’s look at using dox for our API documentation. I also think it would be useful to use ronnjs to generate other documentation. This could be deployed with GitHub pages, and we could look at how to use the GitHub wiki while we’re at it.
Node Roundup: cli, Mongolia, node-openid
Welcome to the Node Roundup. Send in your apps and libraries using our contact form or @dailyjs.
cli
cli (MIT License) by Chris O’Hara is a library for rapidly building Node command line applications. It includes an argument parser, plugin support for adding common options, helper methods to make it easier to work with IO and child processes, colours, progress bars, and auto-completion.
It’s on npm so it’s easily installed with npm install cli.
One of the examples is for sorting a file’s contents:
var cli = require('cli'), options = cli.parse();
cli.withStdinLines(function(lines, newline) {
lines.sort(!options.n ? null : function(a, b) {
return parseInt(a) > parseInt(b);
});
if (options.r) lines.reverse();
this.output(lines.join(newline));
});
This supports -r and -n.
Mongolia
Mongolia by Pau Ramon Revilla is a wrapper for MongoDB with minimal magic. The examples the author gives use simple prototype classes:
var Post = function(db) {
return Model(db, 'posts');
};
var Post = Post(db);
Post.createInstance({ title: 'This is a post' }, function(error, validator) {
// Check validator if set up
});
The API includes methods for embedded objects and validation, so it should provide more bang for buck than the native driver.
It’s also worth pointing out that Mongoose’s 1.0 API looks simpler than the old one, introducing a new chaining-based API.
node-openid
node-openid (MIT License) by Håvard Stranden looks like a great library for OpenID. It supports OpenID 1.1/OpenID 2.0, has a very simple API, and seems much easier to use than the other OpenID libraries I’ve tried.
If you plan on using this library, note that:
To provide a way to save/load association state, you need to mix-in two functions in the openid module (saveAssociation, loadAssociation) … The openid module includes default implementations for these functions using a simple object to store the associations in-memory.
That means the callbacks could be replaced with custom callbacks to save to your favourite SQL or NoSQL databases.
The author has written a blog post about the project here: OpenID for Node.js.
jQuery Roundup: Fullscreen Events, Plugin Skeleton, Wijmo
Welcome to the jQuery roundup. You can send your plugins and articles in for review through our contact form or @dailyjs.
jQuery Fullscreen
jquery.fullscreen.js by Rui Lopes provides event detection when people switch their browser to fullscreen mode:
$(window).bind('fullscreen-on', function(e) {
// Do things that depend on fullscreen
});
This might be useful for building interfaces that adapt to the extra space in fullscreen mode.
The author says it’s only been tested in Chrome and Firefox, and there’s no cross-browser way to trigger fullscreen, but it’s a fairly new plugin so it’ll get updates for more major browsers soon.
jQuery-Plugin-Skeleton
jQuery-Plugin-Skeleton by Oscar Godson is a plugin skeleton. His skeleton includes a license in the plugin’s source, but there aren’t any unit test stubs. I talked to him through GitHub’s messaging system and he seemed to think sample tests might be useful.
My ideal skeleton would look like this:
- README.txt – This should contain fields for things like author name, contact, web site, links to more documentation, license name, contribution submission guidelines
- MIT_LICENSE
- GPL_LICENSE
- unit_test.js – Simple QUnit test stub
- jquery.plugin.js – Similar to Oscar’s example
I imagine readers of this blog wouldn’t usually use a skeleton because they probably know exactly how they want to package their plugins, but it would be nice to get new plugin authors off to a good start.
Wijmo

Wijmo from ComponentOne LLC is an open source (dual MIT, GPL) and commercial kit of jQuery UI widgets. There are a lot of widgets available, including a very modern-looking chart library and cool calendar.
The commercial license is per-developer, at $499, and it’s royalty free. Although I appreciate the massive amount of open source jQuery plugins out there, I think it’s interesting that a developer has built a business model around their plugins (a bit like Sencha).
Wijmo is on GitHub at github.com/wijmo.
Node Tutorial Part 9
Welcome to part 9 of Let’s Make a Web App, a tutorial series about building a web app with Node. This series will walk you through the major areas you’ll need to face when building your own applications. These tutorials are tagged with lmawa.
Previous tutorials:
- Part 1: Introduction
- Part 2: Installation and Skeleton App, source code commit: 4ea936b
- Part 3: RESTful Methods and Testing, source code commit: 39e66cb
- Part 4: Templates, Partials, Creating and Editing Documents, source code commit: f66fdb
- Part 5: Authentication, Sessions, Access Control Middleware, source code commit: 03fe9b
- Part 6: Interface Basics, source code commit: f2261c
- Part 7: Node Library Versions, Jade Tricks, Error Pages, source code commit: 929f5
- Part 8: Flash Messages and Helpers, source code commit: 841a49
Updating connect-mongodb
If you remember back to the start of this series, I had to write a hack to map a mongo connection string to the format connect-mongodb expected. I contacted the author about this through GitHub, and he promptly updated the library to work with connection strings. That means we can scrap mongoStoreConnectionArgs.
Install the version of the package that I’m using:
npm install connect-mongodb@0.1.1
Now update app.js:
// This is near the top of the file in the var declaration
mongoStore = require('connect-mongodb@0.1.1')
// The mongoStoreConnectionArgs function can be removed
// In the app configure block, setting up connect.mongodb looks like this
app.use(express.session({ store: mongoStore(app.set('db-uri')) }));
Remember Me Functionality
Making logins persist in web apps involves some server-side work. It usually works like this:
- When people log in, an extra “remember me” cookie is created
- The cookie contains the username and two random numbers (a series token and a random token)
- These values are also stored in the database
- When someone visits the site who isn’t logged in, if the cookie is present it’s checked against the database. The token is updated and sent back to the user
- If the username matches but the tokens do not, the user is sent a warning and all sessions are removed
- Else the cookie is ignored
This scheme is designed to protect against cookie theft, and is described by Barry Jaspan in Improved Persistent Login Cookie Best Practice.
Building Remember Me
In the models.js file I’ve added a LoginToken model:
mongoose.model('LoginToken', {
properties: ['email', 'series', 'token'],
indexes: [
'email',
'series',
'token'
],
methods: {
randomToken: function() {
return Math.round((new Date().valueOf() * Math.random())) + '';
},
save: function() {
// Automatically create the tokens
this.token = this.randomToken();
this.series = this.randomToken();
this.__super__();
}
},
getters: {
id: function() {
return this._id.toHexString();
}
}
});
exports.LoginToken = function(db) {
return db.model('LoginToken');
};
// Load from app.js like this:
// app.LoginToken = LoginToken = require('./models.js').LoginToken(db);
This is basic Mongoose stuff. It will automatically create the tokens when the model is saved.
Views
Now let’s add a simple bit of Jade to views/sessions/new.jade:
div
label(for='remember_me') Remember me:
input#remember_me(type='checkbox', name='remember_me')
Controller
The session POST method should be updated to create a LoginToken if required:
app.post('/sessions', function(req, res) {
User.find({ email: req.body.user.email }).first(function(user) {
if (user && user.authenticate(req.body.user.password)) {
req.session.user_id = user.id;
// Remember me
if (req.body.remember_me) {
var loginToken = new LoginToken({ email: user.email });
loginToken.save(function() {
res.cookie('logintoken', loginToken.cookieValue, { expires: new Date(Date.now() + 2 * 604800000), path: '/' });
});
}
res.redirect('/documents');
} else {
req.flash('error', 'Incorrect credentials');
res.redirect('/sessions/new');
}
});
});
And the tokens should be removed when logging out:
app.del('/sessions', loadUser, function(req, res) {
if (req.session) {
LoginToken.remove({ email: req.currentUser.email }, function() {});
res.clearCookie('logintoken');
req.session.destroy(function() {});
}
res.redirect('/sessions/new');
});
Express Cookie Tips
The basic Express cookie API works like this:
// Create a cookie:
res.cookie('key', 'value');
// Read a cookie:
req.cookies.key;
// Delete a cookie:
res.clearCookie('key');
The cookie names will always be lowercase. Notice that any write operations are performed on the result being sent back to the browser (res), and read operations are through an object on the request, req
Updating the loadUser Middleware
Now we need to make loadUser check if a LoginToken is present:
function authenticateFromLoginToken(req, res, next) {
var cookie = JSON.parse(req.cookies.logintoken);
LoginToken.find({ email: cookie.email,
series: cookie.series,
token: cookie.token })
.first(function(token) {
if (!token) {
res.redirect('/sessions/new');
return;
}
User.find({ email: token.email }).first(function(user) {
if (user) {
req.session.user_id = user.id;
req.currentUser = user;
token.token = token.randomToken();
token.save(function() {
res.cookie('logintoken', token.cookieValue, { expires: new Date(Date.now() + 2 * 604800000), path: '/' });
next();
});
} else {
res.redirect('/sessions/new');
}
});
});
}
function loadUser(req, res, next) {
if (req.session.user_id) {
User.findById(req.session.user_id, function(user) {
if (user) {
req.currentUser = user;
next();
} else {
res.redirect('/sessions/new');
}
});
} else if (req.cookies.logintoken) {
authenticateFromLoginToken(req, res, next);
} else {
res.redirect('/sessions/new');
}
}
Notice that I’ve put the LoginToken code in its own function. That helps keep loadUser readable.
Conclusion
This is a slightly simplified version of the method suggested by Barry Jaspan, but it’s fairly easy to follow and demonstrates fairly advanced Express cookie handling.
The version of the code I’ve checked in for part 9 is commit 1904c6b.
References
OOP: The Good Parts, JSMag
OOP: The Good Parts
I just finished reading OOP The Good Parts: Message Passing, Duck Typing, Object Composition, and not Inheritance by Nick Fitzgerald. Obvious references to Douglas Crockford’s JavaScript: The Good Parts aside, the article builds on some interesting points by authors like Raganwald that will resonate with many DailyJS readers:
What if code re-use has nothing to do with inheritance, but uses composition, delegation, even old-fashioned helper objects or any technique the programmer deems fit?
Fitzgerald defines a method called quacksLike that he uses to formalize object capability detection and Object.combine for object composition.
These ideas aren’t new, but there’s an interesting code example of a DOM library that uses these methods. It’ll be particularly interesting to fans of Let’s Make a Framework.
functools
While we’re on this topic, functools (documentation) by E. Azer Koçulu is a library for functional programming. He’s tested it with Node, but he says:
Despite functools follows CommonJS specs, my actual aim is to improve the experience of DOM programming
It supports features like iterators, functional composition, currying, and partial function application.
The author is also working on Roka-Lisp, a lisp dialect written in JavaScript.
JSMag

JSMag is a magazine all about JavaScript. The latest issue includes the following articles:
- JavaScript Can’t Do Math! – Rod Paddock
- Sencha Touch – ExtJS and jQtouch – Shea Frederick
- Worlds Collide – JavaScript and Flash Unite – Adrian Pomilio
- Developing Web Applications for the iPad – Jason Gilmore
- Helma Community – ExtJS Integration – Mike Schwartz
- Community News – David Calhoun
The magazine’s PDFs are DRM-free, so you can read them on any device that supports PDF.
Let's Make a Framework: IE Testing
Welcome to part 45 of Let’s Make a Framework, the ongoing series about building a JavaScript framework.
If you haven’t been following along, these articles are tagged with lmaf. The project we’re creating is called Turing.
IE Testing
The way I usually test my projects in IE is with IETester. I actually run this in a virtual machine, just to be safe. Some of my clients still require IE6, some are on 7, and I usually test in 8 and 9 as well. Supporting IE6 is usually the most difficult thing to do, but I usually find JavaScript debugging less painful than design glitches.
I opened IETester and tried running Turing’s tests in IE6 and found they didn’t run. That’s… just life, isn’t it?
To focus a little bit more I tried a simple unit test instead of the whole set. The alias_test.html seemed like a simple one. It produced this error:

It’s probably something to do with the slightly ambitious CommonJS module style test system we created. Note that you can press the escape key to quickly close these IE popup Windows. I tried removing the alias_test.js script and the error didn’t appear, which means there isn’t a problem parsing the files that the test depends on.
After commenting out the code in the test itself, I figured out require was failing somewhere. I used the IETester debug tools to run require('') and the same error popped up. The problem was here, in the Turing Test library:
head[0].insertBefore(scriptTag, head.firstChild);
IE Script Loading
At this point I found IE wouldn’t attach load events to script tags. I dimly recall something about this from Dean Edwards’ posts on window.onload.
This is the kind of issue we had to deal with until the post web 2.0 revolution, but I came up with a scheme to use setInterval to watch for changes on readyState on script tags. This will work in IE, but not in anything else. That gave rise to this:
function loadIEScript() {
var id = '__id_' + (new Date()).valueOf(),
timer,
scriptTag;
document.write('<script id="' + id + '" type="text/javascript" src="' + script + '"></script>');
scriptTag = document.getElementById(id);
timer = setInterval(function() {
if (/loaded|complete/.test(scriptTag.readyState)) {
clearInterval(timer);
tt.doneLoading();
}
}, 10);
}
function loadOtherScript() {
var scriptTag = document.createElement('script'),
head = document.getElementsByTagName('head');
scriptTag.onload = function() { tt.doneLoading(); };
scriptTag.setAttribute('type', 'text/javascript');
scriptTag.setAttribute('src', script);
head[0].insertBefore(scriptTag, head.firstChild);
}
this.loading();
if (document.attachEvent) {
loadIEScript();
} else {
loadOtherScript();
}
The IE code uses document.write to insert a script tag with a unique ID, then it watches for changes to the readyState attribute. Confused? Well, it’s not too difficult to follow this code, but it would be nicer if we didn’t need it.
Here’s the proof it works!

If you’re interested in this area, RequireJS is shaping up to be a good library.
Conclusion
The single unit tests can now actually run in IE, even IE6. There’s still a lot left to do to get full cross-browser support into Turing, but getting the tests going is an important first step.
To get this update, make sure you run git submodule update to get the latest version of the Turing Test project.
References
- IETester
- window.onload by Dean Edwards
- The window.onload Problem – Solved! by Dean Edwards
- RequireJS
