Chapter 1. JavaScript and MooTools

Before we begin our exploration of how to get the most out of JavaScript using the powerful MooTools framework, let's focus a little on JavaScript and MooTools individually. We'll also talk about the JavaScript developer's toolkit, and what you need to develop applications in JavaScript.

JavaScript

JavaScript started out as a small language called Mocha, which was created by Brendan Eich back in May of 1995. Mocha was designed for scripting web pages, and the plan was to bundle it with Netscape's Navigator browser. Before the browser's release, though, Netscape acquired a trademark license from Sun Microsystems to use the name "Java" and the language was renamed to JavaScript. This move was somewhat political on Netscape's part: the release of JavaScript coincided with the new Navigator support for Java, a popular programming language, and the name JavaScript was chosen to market the language as a new and powerful programming language.

This marketing ploy, although somewhat disingenuous since JavaScript and Java bear no relation except for a very superficial similarity in naming conventions and some syntax, was quite successful and JavaScript started gaining traction among web developers. This led Microsoft to create a similar implementation for its Internet Explorer browser, which was released in August of 1996. Microsoft named its language JScript in order to bypass having to license the name Java from Sun Microsystems.

Netscape sought standardization for the language and submitted it to Ecma International for work on the specification, and in June 1997, the first version of ECMAScript was adopted by the Ecma General Assembly. The name ECMAScript was a compromise: None of the parties involved in the standardization wanted to donate their trademark, so Ecma decided to invent a new name for the language.

Note

ECMAScript is the real name of the language as it's described by the Ecma standards and specification; JavaScript and JScript are dialects that have extra features that may not be compatible with the standard. The JavaScript language and its development are now handled by Mozilla, and JScript continues to be developed by Microsoft. For the most part, this book is about ECMAScript, but we'll use the name JavaScript throughout since it's the more popular name.

While JavaScript became popular among web developers, the rest of the programming world dismissed the language as nothing more than a curiosity. This was probably due to the fact that web design was still in its infancy, and most of the developers who used JavaScript were considered amateurs in comparison to other programmers who were developing systems in other languages. JavaScript, being quite new and intended for scripting web pages, was seen as a "toy language" compared with the established languages of the time.

That didn't stunt JavaScript's growth, though, and by 1999 a new specification of ECMAScript was approved and browsers started implementing ECMAScript 3. By 2003, more complex JavaScript-powered web applications started appearing. The huge leap from simple dynamic web pages to powerful web applications was staggering, and JavaScript was once again in the spotlight as the main technology that powered these applications. The revolution finally got its name in 2005 when Jessie James Garrett published his article "Ajax: A New Approach to Web Applications." Ajax, which stands for "Asynchronous JavaScript and XML", became the banner name for several technologies used to create rich and complex web applications—at the top of which was JavaScript. We'll learn more about Ajax in Chapter 11.

JavaScript rose from being a dismissed language to the star of the web. However, as applications became increasingly complex, the need for much more powerful JavaScript implementations became more apparent and browser makers started developing more robust versions of their JavaScript engines. JavaScript development took off from that point, and browser adoption of new features of the most current version of the language (ECMAScript 5, which was approved in December 2009) is growing—and there are a host of other new features still being standardized.

Another milestone was reached in January of 2009 when the CommonJS project was founded with the aim of moving JavaScript outside the web browser. Several CommonJS implementations began to emerge, and it's now possible to create JavaScript applications that run outside the browser and on the server, making JavaScript truly an all-around programming language.

MooTools

During the height of the Ajax period, JavaScript developers realized that some of the programming tasks they were doing were repetitive and could be simplified, so developers started releasing frameworks and libraries that included utility functions for common tasks as well as other helper methods and objects that simplified JavaScript programming. Throughout the years, though, most of these early frameworks and libraries became extinct, but a few of them survived and gained quite a following.

One of those frameworks is MooTools, which had its humble beginnings in a small animation library called Moo.Fx. Back in 2005, the dominant JavaScript framework was Prototype and its effects library called Script.aculo.us. Dissatisfied with Scriptaculous, Valerio Proietti created a new lightweight effects library for Prototype that emphasized code quality and size, and Moo.Fx ended up being only 3KB—uncompressed.

Moo.Fx became the seed that sprouted the MooTools library. While Moo.Fx solved the immediate effects problem with Prototype, the library itself was still a source of dissatisfaction for Valerio and he sought to create a new framework that focused not only on quality and size, but on code modularity as well. Eventually, Moo.Fx became the core of the MooTools effects module, and additional utility functions and modules were added to create a standalone framework. With the release of MooTools 0.87, the framework was born.

The framework gathered a steady community and established a capable team of core developers, and the code underwent several revisions: 1.0 became a milestone release with several new features, and the 1.11 release is still usable today; the 1.2 release marked another milestone, with more modular code and revisions to the base native augmentation code. During preparation of the release that followed 1.2.1, the framework was split into two codebases: MooTools Core, which represented the "core" modules of the framework, and MooTools More, which included the plug-ins and extensions to the core. The launch of the official MooTools Forge in December of 2009 also heralded another milestone for the framework: A web application dedicated to bringing together community-submitted plug-ins, the MooTools Forge opened an official avenue where the MooTools community could share their code.

And with the release of version 1.3, MooTools has once again reinvented itself with a simpler Type system, an improved Class implementation and a fast new selector engine. From its 3 KB beginnings as an effects library, MooTools has grown into one of the best and most powerful JavaScript frameworks around.

The Language Extension

MooTools complements JavaScript in a way that no other library could. When people refer to MooTools, they call it a JavaScript library or a JavaScript framework. Though these descriptions aren't necessarily wrong, they don't encapsulate the main idea behind MooTools—which is to leverage and improve the JavaScript language itself. Therefore, I prefer to call MooTools something else: a language extension.

Developers using MooTools are expected to be JavaScript programmers first, MooTools users second. In the MooTools community, a lot of emphasis is given to learning how to properly write JavaScript, and everyone is expected to know at least the basics of programming. This is because MooTools itself is so intertwined with JavaScript that learning the framework without having a basic grasp of the language would be impossible.

What's often surprising for new users is just how much MooTools feels like native JavaScript. Often, people in the official MooTools IRC channel are asked whether a specific feature is from MooTools or from native JavaScript, and for the most part it's hard to differentiate unless you look at the documentation. Unlike other JavaScript frameworks that impose new rules and syntax on the language, MooTools does not aim to transform JavaScript into another language. It adheres to JavaScript conventions, the syntax and the defined rules, and improves the language by adding new features that leverage and improve the existing ones.

This love for the language itself is apparent in some of the main features of MooTools: the Type system (called Natives in pre-1.3 versions) was created to provide an easier way to augment natives; the Class system was included to simplify object-oriented programming; and the DOM modules were crafted to provide a simpler alternative to its native counterpart for working with web documents. MooTools makes the process of working with JavaScript easier on so many levels and it inspires developers to add more features to the language.

In the chapters that follow you'll see just how much MooTools complements the language. While this is primarily a JavaScript book, MooTools is used as an exemplar of what's possible with the language, and how you—using only the tools available in the language itself—can create complex and powerful new features that add value to JavaScript.

Your Toolkit

Before we venture further, you'll need to get your toolkit together in order to run the example code snippets in this book, as well as to build the arsenal you'll need to develop your own JavaScript applications.

Thankfully, working with JavaScript doesn't require a lot of tools or any complicated software. In fact, much of what you'll need probably came preinstalled on your computer, and some you can easily download for free. So without further ado, here are the components of a JavaScript developer's toolkit.

JavaScript Interpreter

A JavaScript interpreter (or engine) is a program that parses and executes JavaScript programs. You'll need an interpreter that implements at least JavaScript version 1.5, which is equivalent to ECMAScript 3. An ECMAScript 5 conforming interpreter is nice to have, though not necessary.

You don't have to look far to get yourself a usable interpreter: all major graphical web browsers have JavaScript interpreters built in and, due to the recent popularity of the language, turned on by default. At the time of writing, there are five web browsers that have enough marketshare to be classified as "major":

  • Firefox (www.mozilla.com/firefox/)

  • Google Chrome (www.google.com/chrome/)

  • Internet Explorer (www.microsoft.com/windows/internet-explorer/)

  • Opera (www.opera.com/)

  • Safari (www.apple.com/safari/)

Of course, not all browsers are created equal. For working with JavaScript, I recommend Firefox, Chrome, or Safari. These three are the popular choices for JavaScript development because of their support for standards, language implementation completeness, and availability of proper development tools. In fact, an impromptu survey I conducted revealed that these three browsers are the browsers of choice for most developers in the MooTools IRC channel.

Aside from a web browser, you can also obtain a JavaScript interpreter by downloading a CommonJS implementation. These standalone JavaScript interpreters are used for out-of-the-browser JavaScript applications. However, CommonJS implementations lack the necessary environment to run browser-based JavaScript programs, which will be discussed more in Part Two of this book. We'll talk more about these CommonJS implementations and how to get them in Chapter 13.

JavaScript Console

Some of the programs we'll be working with in the first part of this book aren't graphical; they are very basic programs that produce text-based output. In the old days, you might display such text output using the native alert function. However, this could be very obtrusive, and having multiple alert calls in one page could lead to a lot of unnecessary clicking.

Instead, the snippets in this book will use the console object and its log method to display code output. The console object is a special browser object that's exposed by the JavaScript console, which is part of the development tools that come with most browsers these days. The JavaScript console is used to display errors, warnings, and other information about running scripts, and user-generated output can be displayed using a special call to console.log.

Safari and Chrome have a built-in JavaScript Console that can be accessed through the Webkit Web Inspector (called Developer Tools in Chrome). For Safari, you can activate the Web Inspector by going to Preferences

JavaScript Console
Advanced and checking the Show Develop menu in menu bar option. You can then use this menu to access the Web Inspector by selecting the Show Web Inspector menu item. Chrome, on the other hand, has its Developer Tools enabled by default and you can access it by clicking the "wrench menu," then selecting Tools
JavaScript Console
JavaScript Console
(Figure 1-1).

Webkit Web Inspector (Developer Tools) in Chrome

Figure 1.1. Webkit Web Inspector (Developer Tools) in Chrome

Firefox doesn't have a JavaScript console or developer tools built in, but it does have a fantastic developer extension called Firebug (http://getfirebug.com/). Like Webkit's Web Inspector, Firebug is a set of web development tools and includes its own JavaScript console, which can be accessed by clicking the Firebug icon at the status bar or by pressing the F12 key (Figure 1-2).

When running the snippets from this book in your browser, make sure you open up your browser's JavaScript console so you can see the output of the code. Also, take note that the JavaScript console allows you to evaluate code directly by entering it into the input that's provided and hitting the Return or Enter key, giving you a chance to dynamically perform experiments during runtime.

In this book, we'll limit ourselves to using the console.log method for result output. The console object, though, as well as the developer tools themselves, has a rich set of features that are essential to JavaScript development. As these are a bit beyond the scope of this book, I advise you to refer to the browsers' respective documentation for more information.

Firebug's JavaScript Console on Firefox

Figure 1.2. Firebug's JavaScript Console on Firefox

MooTools Core and the Snippet Runner

Since this is a book about MooTools as much as it is a book on JavaScript, you'll need to get yourself a copy of the MooTools framework. The easiest way to do that is to head over to http://mootools.net/download/ and download the prepackaged release.

This book focuses on MooTools Core 1.3, so you'll need to download that version from the site. Older versions of MooTools have incompatibilities with the 1.3 release, so make sure you have the latest version or the snippets and examples in this book might not work. I also recommend you use the uncompressed version of MooTools Core when working with this book so that you'll be able to look at the original source code and so it'll be easier to debug errors that might be thrown from the framework itself.

You'll also need to prepare a "snippet runner," which is a basic HTML page where you can type in the snippet you want to run. It doesn't need to be fancy, and I used this very simple template to execute the code while I was writing this book:

<!doctype html>
<html>
<head>
    <title>Snippet Runner</title>
    <script type="text/javascript" src="path-to-your-mootools-src.js"></script>
    <script type="text/javascript">
        // insert snippet to run here
    </script>
</head>
<body>
</body>
</html>

As you can see, my snippet runner is just a plain HTML page that has two <script> tags: one to link the MooTools source file and the other to contain the snippet I'd like to run. Because most of our output will be displayed in the JavaScript console, no special structures are needed in the script runner.

Code Editor and JSLint

To complete your toolkit, you'll need a proper programmer's editor for writing your code. Because the subject of text editors often brings heated debate, I won't go into a detailed discussion about the pros and cons of each available editor. However, there are certain things an editor needs to be considered usable for our purpose: syntax highlighting, line-number display, and support for JavaScript and HTML.

Note

In case you're wondering, I use Vim (www.vim.org) as my editor for JavaScript development—and for writing this book. (To be exact, I use MacVim: http://code.google.com/p/macvim/.)

Most programmers' editors these days support extensions or plug-ins and, if yours does, make sure you find a way to integrate JSLint into your editor. JSLint is a static code analysis tool that checks your JavaScript code and warns you of any errors you might have failed to notice. Because JSLint can analyze your code without having to execute it, you'll be able to correct errors before you even open your JavaScript interpreter.

JSLint was originally created by Douglas Crockford, and you can find an online version of the tool at www.jslint.com/. You can also download an offline version of JSLint that uses the Java-based Rhino JavaScript interpreter, which you can run on your own computer. However, I recommend you use an alternative implementation called JavaScript Lint or JSL (www.javascriptlint.com/), created by Matthias Miller, that's more flexible than Crockford's original version and uses the C-based Spidermonkey JavaScript interpreter from Mozilla. JSL also has better support for editor integration, and you can find instructions for integrating it into the more popular editors at its site.

JSL uses a config file to tell it which particular rules to check against. Because some of the rules conflict with the standard MooTools style, you'll have to setup your JSL config file to limit warnings regarding MooTools code.

The Wrap Up

Now that we have all of the preliminaries out of the way, it's time to get started on our journey. It's quite a ride we have in front of us, but I'm positive we'll be able to pass through all our pitstops with ease.

Our first destination will take us to functions, one of the best features of the JavaScript language. So if you have your seatbelt buckled, let's start our exploration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset