Congratulations jQuery, winner of Open Source JavaScript Libraries Award

I participated as a judge for Packt Publishing’s open source JavaScript libraries award. Today, they’ve announced the winner: jQuery. Open source JavaScript is stronger than ever, and all of the entrants in the award have made great strides in the past year. Runners-up Raphaël and Mootools deserve great praise for the work they’ve put into both their products and community.

Packt’s press release is below and includes a quote from this blogger.

jQuery wins the 2010 Open Source JavaScript Libraries Award

Birmingham, UK. 18 November 2010

Packt Publishing is pleased to announce that jQuery has won the inaugural Open Source JavaScript Libraries Award category in the 2010 Open Source Awards. The Award is a new category introduced to the Open Source Awards this year, featuring libraries of pre-written JavaScript controls which allow for easier development of RIAs (Rich Internet Applications), visually enhanced applications or smoother server-side JavaScript functionalities.

“On behalf of the entire jQuery Team, let me first say thanks to Packt Publishing for this award.

I’d also like to give a huge thanks to the community of designers and developers that use jQuery daily and felt the urge to vote for jQuery as their favorite JavaScript library. We’ll use this prize to further the development of the jQuery Project.” Said Ralph Whitbeck, jQuery core team member.

“While jQuery hasn’t undergone any radical change in the past year, the project has continued to evolve at the same frenetic pace and the 1.4 release included a wide range of small but important improvements.” Added Michael Mahemoff, Google developer advocate, HTML5/JavaScript specialist and one of the judges for the 2010 Open Source JavaScript Libraries category. “jQuery covers all bases as its performance is high priority, it is easy to use, has a huge community, great documentation, and an excellent plugin ecosystem.”

While jQuery occupied the top spot in the 2010 Open Source JavaScript Libraries category, the other two extremely popular finalists Raphaël and Mootools tied and both projects will be awarded the first runner up position.

With this announcement, the 2010 Open Source Awards has two more categories left, including the Open Source CMS category, for which results will be announced November 19th.

A jQuery Inheritance Experiment

I like jQuery a lot, but I often find myself re-doing my way of OO and inheritance each time I start a new app. And so, I just did it again of course.

I was starting to write a lame HTML5 game, where you have “AlienModels” (of the MVC, not Star Trek, variety), and each with their own “AlienView”. When an AlienModel enter()s, its view will detect a “enter” event and show the alien entering the scene. Certain types of aliens will fly in, certain aliens will fade in, and so on. I started creating an AlienView abstraction, but I figured this is something jQuery can do for me. An AlienView might simply be a jQuery selector. However, this is where jQuery reaches its limits, as I want to call $(“someAlienView”).enter(50,50), and to have the alien’s entry towards co-ordinate (50,50) animated, but animated differently depending on what kind of alien it is.

So I created a framework to do this. Code and Demo here.

The usage is this:

  1. <div class="shy guy">shy</div>
  2. <div class="fly guy">fly</div>

javascript
< view plain text >
  1. $(".shy").define({
  2.       disappear: function() { $(this).slideUp(); }
  3.     });
  4.  
  5.     $(".fly").define({
  6.       disappear: function() {
  7.         $(this).fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn()
  8.                .animate({top: -200 }).hide();
  9.       }
  10.     });
  11.  
  12.     $(".guy").disappear();

When we call $(“.guy”).disappear(), what happens depends on whether this is a “.shy” or a “.fly”. This is basic polymorphism, which jQuery lacks. The $.fn.define() plugin I wrote (see the code in that example) shoehorns it in, but maybe that’s not a good idea…I’m making jQuery into something it’s not. So on IRC someone pointed me to this MooTools-jQuery article. I need to read that article. I also need to get into MooTools, which I think may be more appropriate for this kind of thing, with its unashamed use of prototype (afaict). In general, my urge for more OO and scalable architecture tells me I need to look further afield than jQuery. But syntactic sugar trumps all, so I’ll only go elsewhere if it doesn’t smell of enterprisey, false sense of security, public static voidness.

Incidentally $.fn.define() could go further than I currently have it; it would be possible to set up an inheritance chain, where you could define $(“.guy”).disappear() explicitly, so that if an element matched “.guy” but not “.shy” or “.fly”, it would follow the “.guy” rule. (But not the other way round.) I probably won’t though.

Incidentally (2), thanks @agektmr for telling me about jsdo.it, a mostly-Japanese Javascript pastebin similar toas jsBin and jsFiddle.

Automagic Event Registration

Further to last night’s post on custom events, I’ve set things up now to use “magic event registration”. It’s a little like the auto-wiring facility of a dependency injection container. It’s quite simple really – the app’s initialisation sequence does this:

  • Register all components that might listen to something.
  • Register all events they might listen to.
  • For each listener method among the components, automatically bind the event to it.

In code:

javascript
< view plain text >
  1. var components = [siteFrame, singleTrial, trialController, statsZone, tableView, analysis, rawView, graphView];
  2.   var eventTypes = ["trialCreate", "trialUpdate", "trialSuspend", "trialRun", "trialComplete"];
  3.   $.each(components, function(i,component) {
  4.     $.each(eventTypes, function(i,eventType) {
  5.       var handler = component[eventType];
  6.       if (handler) $(document).bind(eventType, handler);
  7.     });
  8.   })

A component looks like:

javascript
< view plain text >
  1. statsZone = {
  2.   trialCreate: function(e, trial) {
  3.     ...
  4.   },
  5.   trialUpdate: function(e, trial) {
  6.     ...
  7.   }
  8. }

And elsewhere in the code, the events it listens to get triggered through the normal jQuery custom events mechanism:

javascript
< view plain text >
  1. $(document).trigger("trialUpdate", trial);

Part of this is based on what I said last night, which is (a) I’m keeping things simple – hence everything happens at startup and all the instances are singleton classes; (b) consequently, events are global, rather than being attached to any particular component.

Stepping back, what were the alternatives to this design:

  • Components register themselves as listeners – this would be the purist OO answer, i.e. keeping objects autonomous. A perfectly cromulent solution, but a little more redundancy than it needs to be. If objects really do have consistently named listener methods, it’s just as easy to handle registration automagically.

  • The initialisation routine manually wires up components to events. It has a certain Python-like “explicit” feel to it, but again is quite pointless if we can instead do it automagically.

So where does the automagic model fall down? If we are doing things dynamically, it would get more complicated and would, for example, require objects to register upon their creation. So I think that’s still okay. Another problem could be if a single method was listening to more than one event type, since this technique assumes it’s one-to-one from event type to methods. But that’s okay too – I actually had this problem and it was simply solved by getting both handlers to delegate to a third, common, handler:

javascript
< view plain text >
  1. var trialController = {
  2.   trialCompleteOrCreate: function() {
  3.     ...
  4.   }
  5. }
  6. trialController.trialCreate = trialController.trialComplete = trialController.trialCompleteOrCreate;

I realised while working on TiddlySpace there’s a lot to be said for dependency injection style patterns in Javascript, and it’s not happening yet.

Whoa! jQuery’s Adding User Comments to their Docs

I just heard on the new jQuery podcast that jQuery docs will be getting comments. jQuery just got a whole – even more – useful. This is direct from the horse’s mouth, an interview with jQuery head honcho John Resig.

I’ve felt for a long time jQuery has been ahead of the pack with its documentation, and since then both jQuery and its docs have gone from strength to strength.

One thing I was still missing though is user comments.

PHP leads the way here, with the official API docs allowing user comments at the bottom (example). No-one can anticipate all the issues that will arise, so why not open up docs to the developer community? Allowing user comments is also an easy way to help keep the docs up to date (if something of a compromise.) It could also be done as a wiki, if the wiki is managed well. (The Rails wiki is a good example of a well-maintained wiki that receives frequent contributions from people in the know.)

I was missing it until I heard that announcement. Again, jQuery’s leading the way.

I realise there are spam complications, but user comments are a no-brainer for making documentation useful. I continue to derive huge benefit from user comments. (To wit: The user comments about random number seeding were of vital importance in the making of the site I realised earlier today. I use them pretty much every time I have a PHP problem.)

I’ve even thought of making such a project myself, so much did I miss doc based comments.

The docs are being migrated from MediaWiki to WordPress. FWIW I think the OWF could benefit from a similar architecture if the wiki is going to engage with the community. As I’ve learned from AjaxPatterns and maintaining the tiddlywiki comments plugin, most people would rather append comments than updating a wiki. Updating a wiki is intimidating for some, and in any event, requires much more thought in order to make it coherent. Comments tend to be easier to moderate too because of their atomic nature.

Anyway, great news for jQuery and the community!

State of jQuery 2009

Fred noticed Jon Resig’s State of jQuery slides are up:

Highlights for me:

Now:

  • Now using sizzle, the quick, generic (not just JQuery), selector engine. Slide 8 show s almost 2* performance improvement on IE6 from JQuery 1.2.6 -> 1.3.2.
  • Performance improvements are apparently dramatic (browser averages):
    • width() / height() ~4* speedup (good – I need these for http://caption.im8ge.com)
    • hide() / show() ~3* speedup (good – I use them everywhere!)
    • element insert: : ~6* speedup (likewise)
  • Test Swarm is go! Awesome, Awesome initiative. I hope we take advantage of it for TiddlyWiki testing, once it extends to other frameworks. (Or make something similar.)

  • Ridiculous growth and market share (p15-17), and new big sites using JQuery (p13): Whitehouse, Wikipedia, Amazon, Microsoft. Not too shabby eh. Stuff like this makes it much easier for advocates to sell in their organisations.

  • Setting up private CDN on Media Temple, who’s donating all the resources.

Future:

  • More performance improvements in 1.3.3 – p23 shows 3.5x improment over 1.3.2! (perhaps for a subset, but it’s still a big and useful set).
  • JQuery builds optimised for mobile.
  • Moving parts of JQuery UI widget -> core.
  • Four conferences in 2009 – online, London, SF, Boston.
  • Better community sites, inlcuding online forum. Plugin site rewrite.
  • All plugins on CDN..
  • Core -> Github.

JQuery IFrame Plugin

This article by Nick Zakas, covering some technical issues in iframe loading, triggered me to surface a JQuery IFrame plugin I made a little while ago, which supports loading IFrames. (I did tweet it at the time, though I’ve since changed the location.)

JQuery IFrame plugin

The plugin basically tells you, the programmer of the parent document, when your child iframe has loaded. It also has some other bells and whistles, like timing the load duration.

It’s inspired by the use cases of WebWait (http://webwait.com) and the Scrumptious trails player (http://scrumptious.tv). Both are applications whose whole mission in life is to open up an external page in an iframe, and do something when it has loaded.

There’s already an IFrame JQuery plugin, but it’s to do with controlling what’s inside the iframe, i.e. the situation which is only possible when the iframes are from the same domain. What I’m dealing with here is the parent knowing when the iframe is loaded, regardless of when it comes from and agnostic to what it does.

Modal Dialog JQuery Plugin

This has been a while coming, but I made a little “yet another modal dialog lightbox JQuery plugin” thing this week.

Demo and Download for Modal Dialog – JQuery Plugin

It was driven by TiddlyDocs, but I’ve been wanting one anyway for a while. Mostly because lightbox libraries generally do some hocus-pocus on page load, like applying to everything marked rel=”lightbox”, but don’t let you dynamically produce the lightbox yourself. That’s fine for pages that are just a static image gallery, but not useful to someone building a dynamic web app.

I’ve subsequently used nyromodal, on good advice, but wanted something smalller and with a simple API for my main use case, which is just showing some text.

The plugin also simplifies work by not requiring you to install a separate CSS file. Doing that, and linking to it, as well as installing any images, is something that always slows me down when I want to start using a graphical client. In keeping with the “happy path” You-Aint-Gonna-Need-It (YAGNI) mantra, I’d rather keep a library to a single Javascript file – be evil and do styling in the library by default, but still support users who want to put custom CSS in a stylesheet.

Towards A Single Page Application Framework

Tonight, I was thinking of making a Twitter app to manage my various accounts (I have ~dormant accounts related to projects like @webwait and @listoftweets). The app would be holding username and password details for each of these accounts, so it made sense to build it as a Single Page Application (SPA). This way, a more paranoid user could always keep the app in their local file system, while a less paranoid user could always stick the file on a protected server somewhere, having configured all the username-password details.

TiddlyWiki is a framework for developing SPAs. One might say it’s the framework for developing SPAs, since there are no prominent alternatives. So my obvious choice was a TiddlyWiki. However, not too long ago, the TiddlyWiki core guys extracted out the secret sauce for SPAs: the ingenius bit of code that saves files without requiring any browser extensions. (I’ve tried to explain this to people and it always leaves even the most brilliant minds a little dumbstruck, but yes TiddlyWiki demonstrates there are pragmatic hacks that can be used to read a file into the browser and then write it out again.) I was keen to explore this saving mechanism, so experimentation ensued.

The file management techniques ship conveniently in a JQuery plugin, jQuery.twFile. There is a basic demo which lets you edit the entire text and save it. The demo confused me at first – because it was editing the entire body of the file, I wasn’t sure how to translate that info into what I, as an application developer needed. The demo is useful for framework developers understanding the plugin, but less so for application developers. So I extracted it into a demo that is still minimalistic, but closer to the kind of thing you’d do in an application.

The SPA demo is here.

Once I did that, I realised what’s required is a SPA framework. In practice, most developers using twFile will be keeping all the HTML, CSS, and Javascript in a single file, so it’s possible to build a higher-level abstraction on twFile, so that developers can focus only on the content. I built the demo in a way that distinguished what was boilerplate framework code and what was application-specific HTML, CSS, and Javascript.

It was all still in one file, and that’s fine for many developers – you can give the developer the file, tell them “edit these bits”, and they can come up with something functional. I decided to extract things further though, and found the Jinja templating framework to be useful here. Jinja has a concept of template inheritance, so you can easily build up an “include” system. The net effect is I was able to encapsulate SPA logic in a single file, which was passed through a Jinja processor to produce the executable HTML document.

The basic SPA logic is shown below:

  1. {% extends "spa-template.html" %}
  2. {% block title %}JQuery SPA demo{% endblock %}
  3. {% block css %}
  4.   etc etc
  5.   body { background: black; padding: 0; margin: 0; font-family: Gill Sans, sans-serif; }
  6.   h1 { background: white; color: black; padding: 10px 10px 0; margin: 0; height: 52px; }
  7. {% endblock %}
  8. {% block html %}
  9.   <h1>
  10.   <img id="logo" src="data:image/jpeg,%FFetc etc"/>
  11.     <span id="title">JQuery-SPA Demo</span>
  12.   </h1>
  13.  
  14.   <div id="main">
  15.  
  16.     <ol>
  17.       <li>Save this file to your local file system and open your local copy in the browser (using a file:/// URI). The browser might ask for special permission for this document, and you will need to grant it.</li>
  18.  
  19.       <li>Type your message: <input id="message" value="change me"></input></li>
  20.  
  21.       <li>Save this page: <input id="saveButton" value="Save" type="button"></li>
  22.  
  23.       <li>Hit shift-reload to perform a clean reload the page and observe that your message has been saved.</li>
  24.     </ol>
  25.  
  26.     <h3>What is this?</h3>
  27.  
  28.     <p>This is a demo of an experimental Single Page Application I am building atop <a href="http://jquery.tiddlywiki.org/twFile.html">jQuery.twFile</a>, the file saving plugin extracted from TiddlyWiki. Forked from <a href="http://jquery.tiddlywiki.org/twFileDemo.html">this twFile Demo</a>. Only tested on Firefox for now.</p>
  29.  
  30.   </div>
  31. {% endblock %}
  32. {% block javascript %}
  33.     $.spa.save = function(text) {
  34.       return text.replace(/<input id="message".*?></input>/,
  35.               '<input id="message" value="'+$("#message").val()+'"></input>');
  36.     }
  37. {% endblock %}

So it contains separate HTML/CSS/Javascript blocks. Probably not a good engineering practice (though it doesn’t impact on the end-user experience, which is always a single file), but it’s convenient for now. The key SPA logic is here:

  1. <li>Type your message: <input id="message" value="change me"></input></li>
  2.       ....
  3.     $.spa.save = function(text) {
  4.       return text.replace(/<input id="message".*?></input>/,
  5.               '<input id="message" value="'+$("#message").val()+'"></input>');
  6.     }

As an app developer, all you have to do is override $.spa.save (which in retrospect should be renamed as it doesn’t actually perform the save). This function receives the text of the file as it was stored on disk when the page loaded. It must then return the text that should be saved to disk. Thus, it must store application state in HTML, probably by performing some kind of substitution.

Having put this together, I’m keen to proceed with the envisioned Twitter app. It’s not yet clear if there’s any mileage here over a regular TiddlyWiki, but as someone who is more familiar with starting apps from a blank HTML page (or a simple Project Deploy* template), it might end up being a more familiar way to kick an app off. Watch this space.

ColourLovers API – JSON Demos

About a year ago, I was excited to discover ColourLovers had an API. There is some great data about colours and palettes on that site, and some great possibilities for mashups – some as general-purpose art projects, and some as tools for designers.

However, I noticed there was no JSON-P interface, so there was no way to write a pure browser-based mashup. I got in touch with them, and heard back from Chris Williams, who to my pleasant surprise was willing to introduce JSON-P. And so we had some email discussion about the various options for the API interface (e.g. do you call it “jsonp” versus “callback”; do you use “real JSONP” versus just a callback function; do you hardcode the name of the callback function versus let the caller specify it as a parameter), and ultimately Chris went ahead and implemented it a short time later and published the API on January 26, 2009. Fantastic!

I offered to make some demos illustrating code usage, and did around that time, but never got around to publishing them until now. I’ve released the demos here. There’s a couple of JQuery demos, and one raw Javascript demo. I had fun making them and have plans to do a lot more with this API.

TiddlyWeb-JQuery Comments Plugin

TiddlyWeb-JQuery Comments Plugin – Screencast @ Vimeo

I’ve extracted from Scrumptious a nested comments plugin you can integrate into any POJA (plain ol’ Javascript app). You can find it here in the repo: TiddlyWeb-JQuery Comments Plugin.

As the README explains, usage is a one-liner once you’ve set it up. Just do $(selector).comments(“topic”). The topic is an identifier for the set of comments; so that when the UI loads, it pulls down all comments with that ID in its “topic” field. Internally, topic acts as the root of the comments tree…but you don’t really need to know that.

This plugin is a JQuery equivalent of the TiddlyWiki comments plugin, minus some of the more exotic options, and the ability to delete. Eventually, I hope to introduce those things, but only as the need arises – so if you’re using this, please let me know how I can improve it.