The If Works This dirt was a building before

JS.Class 2.1.5 supports Node, Narwhal and more

While there’s much work going on towards what will probably be JS.Class 3.0, the 2.1.x series is benefiting from some of the goodness being added upstream. I’ve just pushed out a new release that gets the package manager and all the libraries to work under CommonJS, specifically targeting Node.js and Narwhal for now.

I’ve had to make one tiny API change to avoid conflicting with the CommonJS API, so require() is now JS.require() and works just like it did before. To get your packages to work under CommonJS platforms, you don’t need to mess around with the exports object, you just need to remember this one rule:

If you want JS.Packages to find your object, do not declare it with var.

I’ll elaborate on this in a future post, but for now just remember that JS.Packages can only work with globally accessible objects, and using the var keyword (even outside a function) under CommonJS only makes the variable visible in the current file. If you stick to this rule and don’t use the exports object, you’ll have code that JS.Packages can run in any environment.

So, to get started using JS.Class on Node, just do what you’ve always done:

JSCLASS_PATH = './path/to/js.class';
require(JSCLASS_PATH + '/loader');

JS.require('JS.SortedSet', function() {
    var set = new JS.SortedSet([3,8,5,9]);
    require('sys').puts(set.count());
});

Note that the require() function is now called JS.require() in order to avoid conflicts with the CommonJS API. I thought about renaming it since I don’t like the fact that putting in the JS namespace makes it look like it can only load parts of JS.Class, but I honestly couldn’t think of a better name for it. Just remember you can load any library you like with it.

As usual, you can download JS.Class from its website.


3 Comments

“using the var keyword (even outside a function) under CommonJS only makes the variable visible in the current file.”

That’s completely implementation-specific and isn’t part of the spec.

Posted by Tobie Langel on 5 June 2010 @ 1pm

Oops. Ignore my previous comment. I misread the sentence completely. That’s of course true.

Posted by Tobie Langel on 5 June 2010 @ 1pm

This is interesting. base2 and JS.Class are very similar. I still don’t like seeing “new Class” though. :)

Posted by Dean Edwards on 8 June 2010 @ 11am

Leave a Comment