JavaScript: How Simple is Too Simple?

The following is republished from the Tech Times #167.

JavaScript: How Simple is Too Simple?

When we first sat down to write Simply JavaScript, Cameron and I had to decide how complicated we wanted to make things. On the one hand, this was to be a beginner’s book, so we wanted to keep things simple (it is called “Simply JavaScript”, after all).

On the other hand, JavaScript isn’t all that simple in the real world, and we felt too many other books were guilty of not giving their readers the tools they needed to understand and write real-world code. We didn’t want to make the same mistake of “dumbing down” the language to produce an easy-to-read book.

To show you what I mean, let’s throw together the same JavaScript example using code at several levels of complexity. The example will be a simple one: we’ll prompt the user to ask whether links to external sites should be opened in a new window. As we’ll see, however, even a simple example like this can get very complicated if you let it!

Simple but Ugly

If code simplicity were the ultimate goal, this example could be very simple indeed:

<a href="" onclick="     if (confirm('Open this link in a new window?')) {'');       return false;     } ">external link</a>

Let’s pause briefly while all the JavaScript veterans in the audience gouge their eyes out.

While this code will certainly work, and would be exceedingly easy to explain in a beginner’s JavaScript book, it’s a very messy solution to the problem. The code is sitting in the middle of the HTML content, and will have to be repeated for every link of this type on the page. Additionally, the URL of the link is repeated in the JavaScript code, which runs the risk of the two getting out of sync.

Still Too Simple?

The code snippet we saw above would have been considered cutting-edge sometime around 1997. Let’s see a more modern alternative that still attempts to keep things simple:

<a href="" class="ext">external link</a> <script type="text/javascript">   var links = document.getElementsByTagName("a");   for (var i = 0; i < links.length; i++) {     var link = links[i];     if (link.className == "ext") {       link.onclick = clickHandler;     }   }    function clickHandler() {     if (confirm("Open this link in a new window?")) {       open(this.href);       return false;     }   }  </script>

Rather than adding JavaScript code directly to every external link in the document, this version uses a single chunk of JavaScript code that detects all of the external links in the document (those with class="ext") and assigns the same JavaScript function (clickHandler) to handle the click event for each. This function can be shared between all the external links, because it uses this.href to fetch the URL to be opened from the link that has been clicked.

Many JavaScript books released in the past few years are content with the improvements that we made in this version of the script. The code is tidy enough, and it behaves as advertised. What more could a beginner ask for?

The problem with this thinking is that beginners who learn from examples like these go out into the wilds of the Web and find examples written using much more advanced JavaScript coding structures, and feel lost.

Simply Better

The main differences between the script we’ve just seen and the sort of code that web professionals are producing in the real world can be summed up in two words: unobtrusive scripting.

Unobtrusive scripting is the name given to a range of techniques that developers use to bundle up their JavaScript code so that it will not interfere with other scripts that may be in play on the same page. The script we have just seen, for example, would interfere with any other script that defined a function named clickHandler, or that registered a click event handler on the links of the page.

Because JavaScript is such a flexible language, there are many tricky ways to achieve unobtrusive scripting. Some popular methods add greatly to the complexity of writing even simple scripts, with references to variables and functions changing dramatically depending on where in the code they occur.

The challenge, when you’re writing a book like Simply JavaScript, is to show beginners how to write unobtrusive scripts without making the code too difficult for the novice programmer to grasp. Here’s what we came up with:

var ExternalLinks = {    init: function() {     var links = document.getElementsByTagName("a");     for (var i = 0; i < links.length; i++) {       var link = links[i];       if (link.className == "ext") {         Core.addEventListener(           link, "click", ExternalLinks.clickHandler);       }     }   },    clickHandler: function(event) {     if (confirm("Open this link in a new window?")) {       open(this.href);       Core.preventDefault(event);     }   }  };  Core.start(ExternalLinks);

The entire script is bundled up inside a JavaScript object called ExternalLinks, which is the only element of the script that could possibly clash with another script, and is consequently chosen to be rather unique. The script is made up of a collection of functions, which are defined as methods of this object.

This structure enables these functions to be called by the same name (e.g. ExternalLinks.clickHandler) wherever they may occur in your code.

Once the script is defined, the whole thing is kicked off by a call to its init method, which is triggered by the final line of the above code, Core.start(ExternalLinks);.

The problem of clashing event handlers is solved by the Core library of functions (Core.start, Core.addEventListener, Core.preventDefault, etc.), the inner workings of which are explained at appropriate points in the book.

While this approach lacks a few of the features of more sophisticated alternatives, it’s simple enough that beginners can grasp it and feel confident writing their own scripts following the same pattern. It also exposes them to more advanced language features like objects, so when the time comes that they need to adopt one of the more advanced coding styles, they stand a good chance of understanding the sample code they will find online.

By using this coding structure from the very first page, Simply JavaScript avoids teaching beginners bad habits. You also don’t get that awkward chapter that occurs around page 100 of several other recent JavaScript titles, where the author explains that the style of code presented up to that point in the book is flawed, and should be avoided.

A Unique Book

JavaScript: How Simple is Too Simple?

If a lot of the intricacies of JavaScript syntax discussed in this post went over your head, I apologize. I do hope, however, that you’ll consider picking up a copy of Simply JavaScript so that you can learn what you’ve been missing!

For those of you that know your JavaScript, I’d love to hear your thoughts on the approach to the language that we took. That, along with coverage of the major JavaScript libraries and our wacky sense of humor, is what makes this book so unique.


Category: javascript Time: 2007-07-11 Views: 2

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.127 (s). 12 q(s)