# JavaScript: How Simple is Too Simple?

The following is republished from the Tech Times #167.

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="http://example.com/" onclick="     if (confirm('Open this link in a new window?')) {       window.open('http://example.com/');       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="http://example.com/" 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

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.

Replay

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

## Related post

• How to do a simple MongoDB find query on LoopbackJS? 2016-02-06

I just want to know how to perform a simple findAll or findOne query on loopbackjs. On a different question someone suggest to me do do something like this: module.exports = function(Transaction) { Transaction.observe('access', function(ctx, next) {

• How to store a simple DB "in the cloud"? 2011-11-06

Even though the name is similar my question is not a dupe of the very fine question here: Database in the cloud? I've got a webserver (Java/Tomcat) running a webapp (which I wrote) on a dedicated server (which I fully configured myself) and I'd like

• How to design this simple DB? 2011-12-27

How to design this simple DB? I need to add some things to a DB I use to keep track of servers. Table looks something like this. Matrix | Name | Description | Etc | Etc | ------------------------------------------------ | Server01 | First Server | Da

• How to write a simple feedback loop in difference equation? 2012-03-08

I know how to write a simple close loop transfer function which is http://en.wikipedia.org/wiki/Control_theory Now I need to do it in difference equation form, like the equation in http://en.wikipedia.org/wiki/Infinite_impulse_response How should I s

• Gimp too complicated; Pinta/GnuPaint/etc. too simple 2012-05-14

I've been looking at a few paint programs, trying to find one that I can use for simple office tasks. Gimp is nice when I need layers or cropping, but apart from that it is a total overkill. I know Gimp is aimed at Photoshop users and it is very powe

• How Can I create simple database in list Sharepoint Fundation? 2012-08-30

How I can create simple database for example vacation request in SP list? It will looks like that: I create probably two list. In first list is vacation days people and on the second list is vacation request and when I add new vacation request I will

• How do I get simple scripts which seem to need root priveliges to run via the www-data user? 2012-09-11

I am programming a small webinterface to control samba on Debian (kernel 2.6.32-5-686). I started by writing simple scripts to add users, create folders, etc. They worked fine when run as root. However, when run via web (apache + php) by using php: s

• How to make a simple fast and lightweight custom screen locker? 2013-10-24

Day to day I'm seeing many questions which say: Screensaver/lock doesn't work. Screensaver doesn't require password after waking or doesn't lock the screen. Can not exit screensaver / nothing works after pressing key or moving mouse. and many many mo

• how to draw the simple geometric figure with arrow shows its width via tex? 2013-11-13

Before I ask this question, I have clicked many pages. Unluckily, I have found none. Could someone tell me how to draw the simple geometric figure with arrow via tex? Be grateful so much! --------------Solutions------------- A strongly recommended ti

• Why the design moves toward simplicity, maybe too simple? 2014-02-21

Around the time when the Windows 8 is out, the design is moving toward simplicity. In Android, in iOS, in everywhere. A rounded rectangle button with visual cues that it's a button, often changed into a simple 1px rectangle with words inside it that

• slide out navigation bar seems too simple but it works, is it? 2014-04-02

http://crystalcleanhomes.com/slide/ There are countless scripts that perform this simple slide-out navigation menu but they are all so bloated and the styles are so convoluted that I decided to make my own and it seems almost too simple and too basic

• How to create this simple model with arrow and text on the top? 2014-05-23

How to create this simple model with arrow and text on the top ? Regards --------------Solutions------------- Without a package and simple LaTeX commands: \documentclass{article} \unitlength=1cm \newcommand\test[2]{% \begin{picture}(3,2) \put(0,0){\l

• How to make a simple collection view with Swift 2015-07-30

I'm trying to learn how to use UICollectionView. The documentation is a little hard to understand and the tutorials that I found were either in Objective C or long complicated projects. When I was learning how to use UITableView, We Swift's How to ma

• How to make a simple countdown timer in meteor, with timer on server and clock on client 2016-01-29

I was wondering how to make a simple countdown timer that would countdown on the server, but show how long was left on the client. --------------Solutions------------- Server: timeToClear.remove({}); //Removes the previous time calls Meteor.setInterv

• how to make a simple function run all the time in c# 2016-01-30

I am a beginner in c#, and I couldn't find out how to make a simple function run all the time in winform. I want to run a function simultaneously with the main code, so that it can lower a stat all the time. how can I do that?(Sorry if this question

• Site too simple for PHP framework? 2016-02-17

I have an existing site in PHP/MySQL that is not currently using a framework. It has a 'roll your own' login/registration functionality. I say the site is simple because the users logging in only have to download documents from the owner of the site.

• How to setup a simple email account to receive emails and fetch them via an ordinary email client? [on hold] 2016-06-23

I have a VPS with Debian Jessie on it running default unconfigured postfix on it. An application is running on this server and it's sending mails on specific events. It was sending them to an gmail mailbox, but since it was sending quite a lot of mai

• How to install the "simple" package in R 2016-01-19

I am trying to follow this tutorial on using R http://wiener.math.csi.cuny.edu/Statistics/R/simpleR/stat019.html One of its snippets references the simple package: simple.lm(cyl,mpg) But where is that package?? > library(simple) Error in library(simp

• How complex is too complex for modals? 2011-10-26

We're in the process of developing an application that makes use of modals to provide the user with extra functionality without having to go to a separate page. I have two questions related to this: 1) How complex is too complex? At what point do you