jQuery Logging

I’ve been having a lovely day at work, fiddling with jQuery. I started to come up with some really gnarly selector chains though, and I wondered what nodes they were actually addressing.

So, I wrote a tiny jQuery extension that logs the current jQuery selection to the firebug console.

  jQuery.fn.log = function (msg) {
      console.log("%s: %o", msg, this);
      return this;

Now, I can just stuff a call to .log() in the middle of what I’m doing to see what I’m currently addressing. e.g.

  $(root).find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");

The nice thing about logging to firebug is that each node becomes clickable in the console, so you can immediately see the context.


Practical Fascism

On my recent project at work, I’ve instigated a number of features:

  • An XSLT stylesheet that strips out all inline JavaScript and inline CSS before it ever hits the browser. Go-go Unobtrusive JavaScript!
  • Lots of jUnit tests:
    • Every piece of static HTML gets validated via RelaxNG (we had to use RelaxNG in order to allow mixed namespaces).
    • Ditto for every piece of XSLT.
    • A well-formedness test for every piece of XML.
    • A jslint test to check every file of JavaScript isn’t doing anything silly.
    • A “no tabs” test to ensure that there are no literal tabs in any piece of source code (in accordance with our local conventions).

I haven’t yet gotten around to integrating checkstyle. And I really need to write an XQuery parser that understands the ancient dialect we seem to be saddled with.

On the whole, these tests have proved to be a minor inconvenience up-front, often leading to groans around the office when the build breaks. But as a whole they’ve kept the code base clean and managed to detect problems early. So on the whole they’re a win. I’ll definitely be dragging them along to my next project.


jslint4java 1.1

I’ve put out a new version of jslint4java. The changes aren’t huge, but there are a couple of note:

  • Fix Issue 1: a NullPointerException when jslint gives up. This is doubly annoying because it’s both documented and it caught me out when writing the Perl wrapper, JavaScript-JSLint.
  • I’ve added an ant task so you can verify a bunch of JavaScript files as part of a built. I was really surprised at how easy this was to throw together.
  • I’ve upgraded to the latest version of jslint. It seems to be pickier about whitespace. I do wish Douglas Crockford kept a changelog…

In the meantime, I’ve also been working on an Eclipse plugin. It’s in a “works for me” state at the moment, and needs some more love before it gets published. In particular, it needs to be able to choose whether or not to validate on a file-by-file basis, in case you have a packed JavaScript file.



A while ago, I wrote a small wrapper around jslint in Perl: JavaScript-JSLint. However, it’s a real pain to use. There’s a dependency on JavaScript, which in turn needs a compiled version of spidermonkey.

On a recent Java project at $WORK, I wanted to use jslint as part of our unit tests—evil JavaScript be gone! I hacked together a small junit test involving Rhino and a filewalker. It’s worked surprisingly well; our JS code has stayed quite readable.

However, I was bugged by the implementation. So, I’ve rewritten it into a slightly more sensible form. This is now available as jslint4java. The main interface is command line, which is nice as it’s completely self-contained now. But there is also an API which lets you call it from unit tests.

  % java -jar jslint+rhino.jar application.js
  jslint:application.js:11:9:Line breaking error ')'.
  jslint:application.js:11:10:Missing semicolon.

It’s also been the first time I’ve used enum classes in Java 5. They’re really cute. Being able to enumerate all possible values at run time is really handy. Plus, being able to define additional methods is really handy.

Future directions include:

  • More help towards integrating this into a junit test easily.
  • An Eclipse plugin would be nice, so that you can get the jslint warnings pop up in the Problems view.

JavaScript URI Objects

I started looking at a dashcode project the other day. Within a few minutes, I realised that I needed something like, in order to resolve URIs into an absolute form. I had a quick look around and there didn’t seem to be anything code out there that does this.

So, I had a quick look at RFC 3986 and noticed that amongst other things it contains pseudo-code for parsing and resolving URLs. I coded it up first in Ruby, which took the pseudo-code almost word for word, and made some tests for it. Then I translated into JavaScript and figured out how to use Test.Simple.

The end result is js-uri, a small URI object. It does what I need at the moment.

  // Parsing.
  var some_uri = new URI("");
  alert(some_uri.authority); //
  alert(some_uri);           //

  // Resolving.
  var blah      = new URI("blah");
  var blah_full = blah.resolve(some_uri);
  alert(blah_full);         //

There’s quite a bit it doesn’t do yet.

  • %-escaping and unescaping.
  • Parsing the URL in more detail. It would be useful to pull out the query parameters and host / port for instance.
  • For some reason, the tests only work in Firefox. Not sure why.

But hopefully it’s still useful.

In the process of developing the JavaScript, I spent ages tracking down one particular problem. I was trying to introduce new scope to define a couple of private helper functions:

  (function () {
      function merge(base, rel_path) { ... }

      function remove_dot_segments(path) { ... }

      URI.prototype.resolve = function (base) {
          var target = new URI();
          // ...
          return target;

Looks perfectly legit right? It caused syntax errors in every browser I tried. Eventually, JSLint managed to tell me the problem: a missing semicolon after the URI.prototype.resolve definition. I hate JavaScript for trying to guess where the semicolon should go. Because it can get it so wrong like this.


Pro JavaScript Techniques

I’ve just finished Pro JavaScript Techniques by John Resig (author of jQuery). It lives up to the name. If you’re a beginner with JavaScript, then look elsewhere. But if you’ve done a little bit before, then this is the book for taking you to the next level.

From the very start, it pulls no punches. It dives right in to talking about Object Oriented JavaScript, a major source of confusion for people arriving from conventional, class-based OO languages. But even in the first few pages, there is already mention of things like firebug, JSAN and Unobtrusive JavaScript. It’s not just the language, the environment and development tools are described. And it’s all bang up to date.

I really appreciate the way that (throughout the book), John will show you how to do something, but then a library which does the same thing (but without the bugs you will inevitably introduce). It’s the best of both worlds: giving you the understanding of what’s going on, but also the ability to use that knowledge quickly.

Further on in part 3, the DOM is described in exacting detail. Yet it’s still succint. Walking through the usual suspect (document.getElementById(), document.getElementsByTagName()), he also goes on to talk about using CSS Selectors and XPath (using external libraries). This is a good example of taking you a step further than most of the other documentation I’ve seen.

Whilst all this is going on, a small library of utillity functions is building up from the examples. Many of these functions are used in later examples. This is something to be aware of if you open the book at random. But, the routines are very likely something you will want to reuse in your own work, so I don’t begrudge this at all.

The chapter on events was a real shocker to me. I thought I had a handle on how events worked in JavaScript, until I read the “Event Phases” section. In particular, I didn’t realise the sequence of events when moving a mouse over nested tags. It’s a small matter, but another example of the accuracy of this book.

Further chapters go on to discuss CSS integration, enhancing forms, and Ajax. There are also practical chapters where you build an image gallery (similiar to lightbox), enhance a blog, build an autocomplete for a text field. These culminate in an Ajax wiki. I have to admit, I haven’t tried the code for that yet. But the design decisions seem clearly explained. I’m not 100% sure on the Ruby code I saw, but that’s a minor matter, as it’s not the books primary focus.

Personally, the chapter on enhancing forms was of the most practical value to the work I do. It was neat, self-contained and immediately usable.

The final chapter is an exploration of the future of JavaScript. John explores JavaScript 1.6 and 1.7 (available now in Firefox), Web Applications 1.0, Comet) and what neat things they will bring.

There are three useful appendices: A DOM reference, an events reference and a brief browser overview. I can easily see myself going back to the first two a great deal.

What negative points are there? Not many. The index seemed a little sparse. In particular, the functions that are developed along the way aren’t in there.

I have no complaints at all about the quality of the writing. It’s all clear and eminently readable. Unsurprisingly, this applies to the code as well as the prose.

Overall, this books gets a big thumbs up from me. I’ll be coming back to it regularly. And I will be nudging work to get a copy as well.


jQuery in Brighton

I went to see Jay Caines-Gooby talk about jQuery last night. It was part of the Sussex Geek Dinner thing. jQuery looks really, really cool. I like prototype, but jQuery looks like it tries to do less. I was particularly impressed at Jay mentioning that the developers were taking features out. There are plugins for people who want more.

But what was really impressive was the revelation that he’d written the presentation itself in jQuery the previous night. Apparently it was about 50 lines of code, which he’d christened “bumnote” (as opposed to keynote), most of which got shown as part of the show. There’s a lot of power in there.

Apparently, it’s also good for making Unobtrusive JavaScript—there was an imposing picture of Jeremy in there.

It’s really good to try and get geeks together in Brighton, and this seems to be working well. I’ve come to realise that there are a large number of technical types in Brighton, but they tend to form in smaller communities. A case in point: yesterday evening I was in the pub with a few members from Brighton LUG (mailing list), and there was no overlap with the geek dinner. There’s at least one big divide between back-end types and front-end types. And then there’s a bunch like Flash Coders Brighton. And the farm.

There appears to be little crossover between all these groups, apart from the BNM list and events like d.Construct. Geek dinners feels nice because it’s starting to appeal to lots more people…


dTrace & JavaScript

dTrace is one of those really, really cool technologies I wish I’d had back when I was a wookie^Wsysadmin. It lets you monitor and profile your system in ways which just weren’t possible before. It’s Solaris only at present, but it’s being ported to FreeBSD and Mac OS X.

But the cool thing is watching people apply it to their favorite languages. Hence, DTrace meets JavaScript. Find out where the time is really being spent in your page…


Decorated JavaScript

I’ve just read The Decorator Pattern for JavaScript. It’s a beautiful example of precisely how flexible a language like JavaScript is. The technique described allows you to run functions before and/or after any function on any object.

The code is fairly understandable as well. When you set up an object as “Decorated”, it adds before() and after() methods. You pass in the name of the function you want run before and another function. Then the magic kicks in. It takes a copy of the original method, and installs a new method in its place which calls all the before hooks, then the original method and finally any after methods.

The only minor disadvantage is that you can’t inspect or alter the return value in the after method. Otherwise, this piece of code is conceptually very similar to Perl’s Hook::LexWrap (a damned fine tool).

I particularly like the way that you can apply the decorator to either all objects or a particular instance thanks to JavaScript’s lovely prototype based OO.

Yes, I’m sure that Dojo gives you all this too. But this is a nice isolated example.


JavaScript on OSX

So, after my little rant a few days ago, I’ve now gotten JavaScript::JSLint up and running. But that involves downloading a lot of Perl modules, and installing SpiderMonkey, which is a none too pleasant task. However, the Mac should already have JavaScript built in—JavaScriptCore, which is part of WebKit, which is used to build Safari.

So, I’ve spent an interesting couple of days learning Objective-C, Cocoa and nosing around the Apple developer documentation in order to see how to get at the JavaScriptCore. And, as far as I can see, you can’t.

The best I came up with is Using JavaScript From Objective-C. Which sounds nice and well, but from what I can make out, it’s predicated on having a window hanging around, which I want to avoid (I want a command line tool). It also doesn’t provide any interfaces to bind your own functions into the JavaScript interpreter.

Now, JavaScriptCore happens to be one of the Open Source parts of OSX. So, I can just download it, build my own wrapper, and so on. But it is annoying that I have to do so when the system comes with a perfectly good JavaScript interpreter of its own. Not only that, but it’s an alternative implementation to spidermonkey (based on KJS from KDE). And more implementations usually leads to a healthier ecosystem for a programming language.

In the meantime, anybody wanting (relatively) quick access to a lint for JavaScript on osx should probably look at javascriptlint instead. It still needs compiling, but it produces a single file which has no dependencies.

Mind you, I’m still glad at the time I’ve spent. Objective-C is rather nice (apart from the lack of garbage collection—refcounts make me nervous). And Interface Builder is the nicest GUI builder I’ve yet seen. Or at least it’s the only one that didn’t make me run away screaming.

Update: Looks like I missed JavaScript OSA. But that doesn’t look like it’s been updated in years.