9/05/2012

JavaScript, Frameworks, CoffeeScript, ClojureScript, Dart

Introduced in Netscape Navigator 2.0 in 1995 and adopted by Microsoft Internet Explorer 3.0 as JScript in 1996, JavaScript - or ECMAScript, the name of the vendor-independent standards first published in 1997 - has had many faces: It was a useful toolset to accomplish web developers' tasks, it got misused to just annoy the user, it was misunderstood and brought barriers into websites, but maybe the most important: It is the engine powering many innovations in web development. To just name a couple of buzzwords connected with JavaScript backstage: Ajax, SaaS, HTML5.

But let's start at the beginning: What are classic use cases for JavaScript? One of the most popular now and then is the good old form validation. Consider a form where the user is meant to input a name and an amount. The following function could be used to check that both fields have values and that the later one is positive (and actually a number):

function isValid() {
  return document.forms[0].elements[0].value.length && documents.forms[0].elements[1].value > 0;
}

The function could then be used by the submit event handler for the form element. E. g. you could add the attribute onsubmit="return isValid();" to the form element, which would install a handler returning the value of the validation function. If the handler returns false, the submission is canceled by the browser, otherwise it continues as if the handler wasn't even present.

Other use cases include changing, adding and removing (or hiding) elements from the document tree. E. g. activating a radio button (which fires a change event) could update a price tag or show another element. Of course, these use cases make much more sense as soon as the script is able to fetch additional data. This is what's called Ajax. Ajax, which stands for Asynchronous JavaScript and XML, was introduced by Microsoft Internet Explorer 5 as and ActiveX control called XMLHTTP and adopted by other major browsers as a native JavaScript object called XMLHttpRequest, which in terms is available in Internet Explorer as of version 7. It basically means that an HTTP request, just like the ones triggered by clicking a hyperlink, is sent in the background and the response is made available to the JavaScript code that triggered it. A simple use case may be a self refreshing page view counter, which fetches the current value every few seconds and replaces the old text with it. This would typically be done by simply transferring the plain value, without using XML. XML is actually rarely used in Ajax - more complex protocols often use JSON as a representation. A simple JSON example:

{
    "firstname": "John",
    "lastname": "Doe"
}

The braces delimit an object , firstname and lastname are elements of that object and John and Doe their respective values. This can simply be transformed into the represented JavaScript object by the eval function. JSON can also represent arrays (using brackets) and is of course aware of different simple types like strings, numbers, booleans and the null value.

Together with the possibility to move and resize website elements (manipulating their style values), Ajax also enables rich user interfaces in terms of Software as a Service (SaaS). One can think of e. g. a complete office software suite in the browser. Other common Ajax uses include auto-completion of search terms.

There are many frameworks to ease the use of JavaScript, sometimes referred to as DOM manipulation frameworks. They bring a short syntax for addressing specific elements, ease event handling, provide functions to e. g. resize, move or hide elements, handle Ajax and much more. The most popular one is JQuery. Other comparable frameworks include Dojo, Prototype,YUI, ExtJS and MooTools. Each of them has its specific features like custom elements (sliders e. g.) or e. g. a tiling engine, so its not uncommon to use more than one. W3Techs has some usage statistics on JavaScript libraries.

The current innovation in web development is HTML5, which is another major step for JavaScript. HTML5 is indeed not that much about the markup, but much more about new, common (JavaScript) APIs. Important HTML5 APIs address 2D drawing (canvas), offline applications, Web Storage, drag-and-drop, cross-document messaging and much more. Other specifications not directly belonging to HTML5, but obviously connected with it, include e. g. Geolocation and the File API. In some cases, like the File API or drag-and-drop capabilities, this eases and unifies common practices, in other cases like Geolocation or offline capabilities, this enables applications which weren't achievable yet without any native component.

In conjunction with HTML5, the overall structure of web applications has changed. In the classic model, e. g. represented by the Ruby on Rails framework, you have controllers, handling (HTTP) requests, using models (i. e. data) and rendering views. Modern HTML5 applications shift controllers and views to the client. Instead of an HTTP request for a new view, a user action is now handled by the JavaScript code present in the client. It knows how to act on it and what view to render. Only the data (models) are still on the central web server and requested by the client code. Benefits of this include less requests, less server load and the possibility to use the application offline with stored data. This can even replace native applications and is already highly deployed. HTML5 is the primary way to develop applications for HP's Linux-based tablet system webOS, which was just open sourced, and the only way to develop applications for Tizen, Intel's and Samsung's successor for the mobile Linux system MeeGo (in terms successor of Maemo and Moblin). Many cross-platform mobile apps for systems like Android and iOS are only small native frameworks while the actual content is provided by an HTML5 application. Since this may of course lead to performance issues, some of the big players, like Facebook on iOS, are actually backpedaling to more native code. It's also a major task to provide a cross-platform app without violating platform-specific user interface habits too much.

Nevertheless there's a shift from servers to clients, which brings the need for client-side MV* (Model, View, "Something") frameworks as well as for simple server-side technologies, since the usual MVC frameworks are definitely overkill when only implementing very simple controllers and no views at all. For HTML5 applications only requesting data sets, the server-side code only needs to mash models, e. g. take a user object and his corresponding posts and create a data set needed for his profile page, which is then e. g. JSON-encoded. This is the field taken by a new technology called node.js. LinkedIn's Kiran Prasad gave a classifying talk about this shift and the role of node.js at DevCon5. He also mentions the two major pros and cons of node.js: It's JavaScript and it's completely based on events. Both of this characteristics you either love or hate. I'll take a look at node.js later in this series.

Let's switch back to the client side. There's a damn huge variety of MV*  frameworks out there, so if you're curious, just take the Journey through the JavaScript MVC Jungle by Addy Osmani, one of the creators of TodoMVC. TodoMVC is a great comparison for those frameworks. It implements a given Todo application with a huge list of frameworks, including the popular Backbone.js, AngularJS, Ember.js, Spine, KnockoutJS, as well as the already mentioned Dojo and YUI frameworks and many others. Steven Sanderson gives another useful overview of the most popular ones.

As mentioned in my post about HTML and CSS meta languages, there's a similar one for JavaScript, which is called CoffeeScript. CoffeeScript brings a nicer syntax to JavaScript and works similar as e. g. SASS, i. e. it's compiled to JavaScript manually or sever-side before being shipped to the client. The CoffeeScript syntax is inspired by Ruby and Python, so it especially targets developers using those languages in the backend. It was initially implemented in Ruby, but is now itself written in CoffeeScript and can be compiled and run on a JavaScript engine like Google's V8 or Mozilla's Rhino. A similar project is ClojureScript, which is a subset of the functional Clojure language and can be compiled to JavaScript as well. A completely different approach was introduced by Google as Dart. Although Dart can be compiled to JavaScript, it's indeed meant as an alternative and to be run by the browser as is. There is Dartium, a special version of Chromium able to run Dart scripts, and Google plans to bring it to Chrome / Chromium, but none of the other browser vendors has mentioned any plans to support it. Of course, there are other projects out there, like the Saltarelle C# to JavaScript Compiler.

That's it for the basic technologies. Next, I'll have a look at browsers. But first, I'm on holiday for the next two weeks.

No comments:

Post a Comment