Django 1.0 released!

Wohoo! OK, maybe not as big as Chrome but Django 1.0 released yesterday! Django is a brilliant Python Web framework designed to make our lives easier. Django takes DRY to its extreme and comes with myraids of documentation including an online book! Django is like Lego, first you start with many dispersed pieces; you then get an idea of what you want to build; pick up a few pieces from Django Plugables; and tada! Your masterpiece is near completion.

I know I sound like a salesman now but I'm really just trying to express my excitment to the 1.0 release :)

Now, it's time to get my hands dirty with Python!

Google Chrome

As you may have heard Google Chrome (Chrome) went live yesterday. The Chrome team also released a comic explaining some of the innovations and ideas around Chrome.

After installing Chrome the first impression I got was it's a very slim-line and compact browser. The UI reflects this totally. There isn't the usual File menu above (personally I don't think it's needed in a browser anyway) and tabbing is at the very top. The Omnibox, Chrome's address bar, is very dominant and a very powerful. Much like Vista start search feature you don't have to remember where things are — just search for it. The default search engine of the Omnibox does not have to be Google either, use "Options -> Basics -> Default search" to change it.

I really like the Application shortcuts feature. Many a time I have wanted a shortcut on my desktop which opens up a web application much like a desktop app does. I know you could create a lnk file and place that on the deskopt but somehow it doesn't feel good. When you create an application shortcut however it creates for you a special shortcut which opens up Chrome in an even slimmer interface that looks just like a standard desktop application. It is excellent when used in twine with GMail.

Gmail in Google Chrome

Chrome is a muti-threaded browser, that means each instance (new tab, new window, plugin, javascript etc) runs a separate process, it sounds like a wasteful approach but quite a fascinating concept as explained in the comic. It uses the tried and tested WebKit engine for rendering web pages and the V8 JavaScript engine. V8 is a high performance engine written in C++ which compiles and executes JavaScript code. All are open source projects so not an inch of propreitary code inside!

I think Google is on to a winner, if not, they have once again set the bar higher for others to compete against.

Barcamp Hong Kong

The second coming of Barcamp Hong Kong has arrived. I'm a bit late to the party because somehow I've been dropped off the mailing list — someone does not like me :)

Anyway, do not fret! There is still one week left until the event so RSVP now!

barcamp Hong Kong 2008

jQuery.com website redesign

The long overdue redesign of jQuery.com has finally landed! I like the new design as it's more intuitive and inline with jQuery UI's design. This redesign will certainly help pitch jQuery to new comers; for many the decision to go with another framework has purely been based on the ugliness of the old jQuery website, that should hopefully change now.

Old:
old jQuery.com design

New:
new jQuery.com design

However, I still see much room for improvement. The website clearly lacks that magical touch you could easily achieve with a sprinkle of FX and UI. The fade-in boxes on the homepage don't work for me and display erratically when you mouse over them quickly. Hopefully the jQuery team will change this soon.

That said, hats off to the team as they have done an excellent job, as always, in giving us this redesign and of course — jQuery. Thanks!

jQuery: Shuffle Plugin

I recently came across a really compact array shuffling function on JSFromHell.com, which I thought would make a nifty jQuery plugin.

This jQuery shuffle plugin could be applied to any HTML element or Array object.

(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  }

  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
})(jQuery);

Due to line wrapping issues in this post I inserted a few hard carriage returns in the above snippet (sorry).

Example 1: shuffle an unordered list

$('ul').shuffle();

Example 2: shuffle an array

var arr = [1,2,3,4,5,6];
arr = $.shuffle(arr);

There is a demo here. And for those interested I encourage you to download the plugin for closer inspection.

JavaScript: Event Delegation

Recently, I've been hearing much about event delegation. Many new to this concept seem to be baffled by the term. However, it really is a simple idea when you realise what's involved.

Put simply, event delegation is the practice of directing events on parent DOM elements who then listen on their children for events.

To understand event delegation and why it works you should read this ppk article before continuing — JavaScript Event Order.

Back? OK, so now you know about event capturing and bubbling the concept is easier to comprehend.

Event delegation takes advantage of the fact that actions performed on a child element always bubbles up to the top. Traditionally events are handled on the element that fired it, for example (excuse my jQuery) :

$('button').click(function(e) {
  alert('You clicked on me?');
});

Now rather than handling the click event shown above on the element itself we could delegate it to a parent because we know all events eventually bubble to the top, so

$('html').click(function(e) {
  if ( $(e.target).is('button') )
    alert('You clicked on me?');
});

produces the same result as the first code snippet.

Did you notice e.target? This is the essence of event delegation. As the event bubbles it keeps a mental note of its starting position in its pocket; e.target is a reference to the first element the event started bubbling from. In the above code sample that would be button.

That's event delegation in a nutshell!

Now, you might be asking - why should I use this rather than traditional one-to-one event handling?

Here are a few reasons:

  • In event delegation you bind one event handler to handle events on multiple elements. In traditional event handling you have to create a thousand event handlers to handle a thousand events. As you would expect event delegation is less resource expensive and could result in quicker response times
  • If Ajax or DOM manipulation happens, re-binding event handlers usually follow. Event delegation avoids re-binding by listening to a parent you know won't be manipulated, i.e. html, body or the website container.
  • Event delegation makes for cleaner code if you have a large webapp demanding lots of event handling.
  • No need to worry about event order and bubbling issues as we're now taking advantage of this effect

In conclusion. Event delegation is not a replacement for Event handling - both have their uses depending on situation. Event delegation requires more planning and could be harder to debug due to the inherent abstractions. You just can't beat the humble event handler if all you want is a link opening in a new browser window. That said, you'd be mad not to use it if you have a complex app with thousands of event objects doing various operations from submitting a form to loading Ajax content.

Further reading:

jQuery UI Spinner

After contributing jQuery Numeric Stepper to the jQuery UI community. Paul Bakaus kindly asked whether I'd like to merge it with the official jQuery UI Spinner, of which I was more than happy to do out of pure love for jQuery.

The jQuery UI Spinner widget will be available with the soon to be released jQuery UI v1.6.

Here's a demo of the current incarnation.

Also, check out Subversion if you're interested in getting the latest and greatest.

Update: this spin control is currently in re-design phase and will come under intense refactoring to be leaner and meaner. So the UI team have decided to push back its release to v1.next, which means it will not be part of the final 1.6 release. Sorry guys!

Update2: I've posted an update on this here.

jQuery: outerHTML

The outerHTML property (IE only) could sometimes be very handy, especially if you're trying to replace an element entirely. Brandon Aaron has very kindly given us a outerHTML plugin that does half the job as it doesn't support replacements. The following code snippet fills in the blanks:

jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}

To get the outerHTML value of an element do this...

$('#myTag').outerHTML();

To replace #myTag entirely do this...

$('#myTag').outerHTML("<p>My brand new #myTag.</p>");

Hope this helps someone :)

Update: There's now a demo page.

jQuery Numeric Stepper

As an experiement I ported over my Accessible Numeric Stepper into a jQuery widget and added some accessibility enhancements and new features in the process.

This widget utilises ui.core.js - a factory method object for creating widget classes. Widgets in jQuery are essentially plugins at heart but built to follow stricter coding standards in order to unify the underlying quality between developers. It also adds convenient mouse interaction classes and option settings among other things.

The result is jQuery Numeric Stepper an unofficial jQuery UI widget. Features include:

  • min, max, start and step size settings
  • supports decimal values and decimal step sizes
  • supports currency values
  • keyboard and mousewheel interaction - increment/decrement values via cursor keys, +/- keys and mousewheel

Download latest source code here

Bugs? Missing feature? Code improvements? Let me know!

Update: Features seen here are now part of the official jQuery UI Spinner, set for the 1.6 release of jQuery UI. More details.

Banana Apple Orange?

Which do you prefer? maybe all? maybe none? It's totally up to you and down to individual preference. The same could be said for Web Frameworks. This choice has come at a time when I am deciding on a Web Framework to use for a number of projects. So this post should hopefully put some sense into the one I go for...

So what is a web framework?

A Web Framework, short for Web Application Framework, is a collection of re-usable and easily extendable code in which developers could build web applications. A framework takes care of all the mundane tasks involved in development and follow well practiced methodologies such as MVC, KISS, DRY or any other code of practice of the framework authors choosing. A good web framework removes the head-banging, keyboard-bashing, screen-swearing parts of day-to-day development leaving you with just the fun bits. ;)

There are a lot of web frameworks, as there are fruits. The three that most interest me at the moment are: Ruby on Rails, Django and The Zend Framework.

Ruby on Rails (RoR)

RoR is like the street kid of the Web; lovers of skateboards and graffiti; Cool, trendy and think they are the best! RoR is a full-stack Web Framework, meaning you either use it entirely or not.

RoR is very well documented with many popular web applications running on it.

Django

Django is like the new kid on the block with a rich dad. Django has actually been around for quite some time, born more or less the same time as RoR but has been living in obscurity. The recent news of Google AppEngine and its preference for Python has really boosted the Django community. Django was written entirely in Python from scratch even though there are myriads of existing Python libraries doing the same web tasks disparately.

Django comes built-in with an Administration area which is a big plus over RoR as in most cases there needs to be some sort of secure area for the client or customer. Django makes that easy.

The Zend Framework (ZF)

ZF is like a typical kid who gets the grades and progresses through high school without problems. PHP is about being everywhere and catering for everyone. ZF is slightly different to the other two as it's more a library of components rather than a full-stack framework. You use what you need and could even integrate any component into existing frameworks such as CakePHP or CI. ZF is also powerful enough to be a full-stack framework in itself if you choose to build your entire web application on it.

Myth

It is a typical myth that using RoR instantaneously means you have a winning solution and enforces you to create cool & friendly websites. The fact of the matter is Rails has been marketed so well and hyped to a point it has attracted all the cool street kids who are using their graffiti skills on Rails. If these kids chose PHP or Django or whatever, they will produce the same stunning results because of their exceptional talent, not the framework they chose.

Lastly...

Something that annoys me immensely is when people compare frameworks with snotty remarks like "My one is better than yours", "That framework is totally un-cool", "Using my framework you can do this in 5 mins, how long does it take in yours?"

As with the recent consensus between JavaScript pioneers; it does not matter what javascript library you use or choose not to use. The key is to use one that's right for you, your team and the project. I tend to take this stance with my frameworks too.

Obviously a framework promoting rapid development and prototyping, such as RoR and Django, makes development easier and helps developers concentrate on the more important aspects of a website - user interaction and website architecture.

Lastly, my choice is Django; at least for the current projects in hand anyway. ;)