ePub ‘MVC applies to JavaScript’ released

21/02/2013 § 5 Comments

MVC applies to JavaScript

Glad to announce that Developer.press released my first ePub: ‘MVC applies to JavaScript’. The ebook is about integrating the MVC pattern into JavaScript development. It presents a pragmatic approach on how you can develop a client-side application using this pattern. Real code is possibly the best way to explain the advantages of using a design pattern and this book shows a comparison of the code needed to build a sample application adopting and not adopting MVC.

Backbone.js, one of the most popular MVC/MV* frameworks, it is also brought as term of comparison. The sample application mentioned previously is built using Backbone.js to show how the use of a framework can help and speed up your development process.
Client-side applications are becoming larger and larger and having a pattern to use as a guideline can definitely be very advantageous for producing maintainable and scalable applications.

The book is available on Amazon and on Itunes for less than $2.

What’s there behind a “class” in CoffeeScript?

17/03/2012 § Leave a comment

CoffeeScript is a little language that compiles into JavaScript. CoffeeScript is gaining lots of popularity due to its simplicity and it is really popular in the Ruby community having lots of similarity with Ruby. CoffeeScript comes with the notion of “class“. Class?? JavaScript doesn’t have class, right? True, but JavaScript has the concept of inheritance built-in the language. JavaScript doesn’t use classes for inheritance, but it uses the “prototype” object as you may know. Prototypal inheritance can be implemented in JS as the “Object.create” method (available in ES5) does or as in the protoInherit() in the following snippet:

// parent object
var parentObj = {
  prop1 : "value1",
  method1 : function(){ return 1;}

// prototypal inheritance through the protoInherit function
function protoInherit(parentObj) {
  function Temp(){};
  Temp.prototype = parentObj;
  return new Temp();

// child object inherits from parent
var childObj = protoInherit(parentObj);

console.log(childObj.prop1); // returns "value1"
console.log(childObj.method1()); // return 1

Quite straightforward: the prototype linked to the new object points to the object that we want to inherit from. In this way the new object gets all the properties and methods from the parent  object name “parentObj” in the previous snippet.

Now, let’s go back to CoffeeScript. If you visit http://coffeescript.org/ and you scroll down to the section “Classes, Inheritance, and Super“, you can see in the right hand how the inheritance is implemented and how a CoffeeScript class is translated into JavaScript. The method that is in charge of expressing inheritance is “__extends” and below is the implementation used:

__hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) {
  for (var key in parent) {
    if (__hasProp.call(parent, key))
      child[key] = parent[key];

  function ctor() {
    this.constructor = child;
  ctor.prototype = parent.prototype;
  child.prototype = new ctor;
  child.__super__ = parent.prototype;
  return child;

Not exactly the same code as in the previous snippet. Look confusing? Let’s have a better look. The function implementing the inheritance takes the “child” and the “parent” function as arguments. First of all, all the properties from the “parent” are copied in the “child” function. Then, the prototype object of the “child” function points to a temporary constructor, which prototype points to the “parent”‘s prototype. The “__super__” property is attached to the “child” function and it points to the parent’s prototype, in case you need to refer to the parent function. Finally the “child” function is returned.

Basically the classical inheritance pattern has been implemented here and it is an alternative to express inheritance in JavaScript. It makes sense in this context as CoffeeScript is trying here to emulate the behaviour of classes, familiar for Ruby, Java or C# developers, and to hide the prototype’s behaviour, which can be confusing for non-JavaScript developers.

I personally still like using the “prototype” object for inheritance, as it seems more a native thing from the language. Anyway, hope to have clarified the meaning of the code behind a “class” in CoffeeScript.

Singleton pattern in Java and JavaScript

01/02/2011 § Leave a comment

Singleton pattern is a Design Pattern that uses a single instance of the same class. It’s used where we need just an object, an instance which we can call through the whole application. In Java, a typical example where this pattern is commonly used is when we use the logging functionality (Log4j, Commons Logging, SLF4J..), where we need a single instance of the Logger object.

In Java, we can implement this pattern typically in two ways:

a) The Singleton Class has a public, static and final field that get the instance and a private constructor

    public class SingletonClass {
        private static final SingletonClass INSTANCE = new SingletonClass();
        private SingletonClass(){};

You can call the object as “SingletonClass.INSTANCE“.

This first approach is not completely safe though (see AccessibleObject.setAccessible method to call the private constructor).
To avoid that, we can look into the second type of approach:

b) The Singleton Class has a public static method that return the instance (factory method), a private constructor and a private field that instantiates the single instance.

    public class SingletonClass {
        public static final SingletonClass INSTANCE = new SingletonClass();
        private SingletonClass(){};
        public static SingletonClass getInstance(){return INSTANCE;}

You can call the object as “SingletonClass.getInstance()” and it gives you more flexibility around the API.

From Java 1.5, the best approach according to Joshua Bloch, is using the enum type.

    public enum SingletonClass {

You can call the object as “SingletonClass.INSTANCE“, very similar to the first solution shown. This approach appears to be the best especially when you need to deal with Serialization and Synchronization.

In JavaScript, it’s of course possible to implement this pattern as in Java. That is how the code can look:

    var SingletonClass = (function(){
        function SingletonClass() {
            //do stuff
        var instance;
        return = {
            getInstance: function(){
                 if (instance === undefined) {
                     instance = new SingletonClass();
                return instance;

You can call the object as SingletonClass.getInstance().
The code looks really similar to the way the Singleton used to be implemented in Java, where the main problem is dealing with Threads & Synchronized blocks (having a similar code in Java, it will cause an issue in an environment with multiple threads).

JavaScript fortunately is single-threaded, so we don’t need to worry about this kind of problems.

For more info, you can read the article from the wiki

Reasons why I wrote the plugin Jquery Asynchronous Image Loader (JAIL)

04/01/2011 § 13 Comments

The need for a plugin that loads images asynchronously comes from the will of improving the page load time and making the user experience enjoyable/acceptable when there are heavy images
in a page. When there are images on a page, the browser makes HTTP requests to download them and in case there are many of them and they have
large size, it can take a while to load the rest of the page. The user will see the content below the images with some delay and the user experience won’t be that pleasant.
In mobile sites, I find this problem quite critical, as the user will especially feel the effects of this delay.

Deferring the loading of the images can be the solution and that’s what my plugin is about.

Before to have started writing it though, I researched on the net if there was something already that could solve my issue. Well, of course someone else has already thought about this problem and has already implemented something good. That’s what I found:

YUI ImageLoader Utility : utility from YUI3, that delays the loading of the images and
lets you determine triggers and time limits to initiate image loading. You can find more info on their web page and I believe it’s a great utility (like all YUI3 library great code as well)
This utility requires some HTML change, such as leaving out the “src” attribute from the IMG tag.

There are few things about this solution that weren’t good for my purpose though (in order of importance):
a) Disabling JavaScript, the images are not loaded. That was surprising! They didn’t care about progressive enhancement.
b) I can customize a trigger to load the images, but I can’t customize a callback function after the images are loaded.
c) I’ve already got jQuery in my page, I’d like not use another JS library for page performance reasons. (other JS code to download)

Lazy Loading Plugin for jQuery : plugin for jQuery written by Mika Tuupola.
This solution was respecting the progressive enhancement and was solving above a) and c)! It seems the way to go.
Just a couple of things go bad:
a) In the homepage it’s clearly written that the plugin is currently not usable.😦
b) Refreshing the demo page with the Net tab of Firebug opened, the images “below” the fold are loaded.
So something must go wrong at least in my browser FF 3.6 on Mac.

I decided to take notes from this previous solutions and in order to achieve what I needed for the site I was working on, I wrote my own plugin for jQuery, called
JAIL aka Jquery Asynchronous Image Loader. The whole solution respects the concept of progressive enhancement, you can customize a callback function and it requires jQuery of course.

You can find the source on Github and the project homepage here.

It’s lightweight (compressed version is 4Kb), it’s licensed under MIT and GPL v3 and it’s been tested with jQuery 1.3.2+ on FF2+, IE6+, Chrome5+, Opera 10+, Safari3+.

Just some quick notes, this plugin is not for all the cases and it’s not supposed to be applied to all the images. It required some HTML changes so you need to be able
to modify the HTML, and I’d suggest to use it for “heavy” images and for mobile sites.

UPDATE (19/12/2011) : Version 0.7 released. Added support for ‘offset’ configuration

UPDATE (03/04/2011) : Version 0.8 released – jail() function, fixed critical issue on v0.7, resizing function, scrolling fixes

UPDATE (03/08/2011) : Version 0.9.5 released – Issue 14 fixed regarding applying event on container different from ‘window’, filenames changed.

Enumeration in JavaScript

07/12/2010 § Leave a comment

In the previous post, I mentioned that I would have talked about the “FOR-IN loop” in this post, and that’s what I’m about to do. So reading the title, you can gather how “for-in” loop is used for Enumeration in JavaScript.

What does it mean?

It means that if you want to enumerate the properties inside a JavaScript object, you need to use this type of loop. This is an example:

// Object literal
var myObject = {
    field : "myfield",
    mymethod : function(){
        return "hello";

// for-in loop
for (i in myObject) {
    console.log(i) //"field", "mymethod"

The console will print the properties of the object, so the field and the method.

Coming back to my previous post, one of the issue with this loop is that is taking under consideration even all the objects involved in the prototypal chain, so that if we augment the Object with a new property the for-in loop will consider even this last one.

Object.prototype.newMethod = "string";
// Object literal
var myObject = {
    field : "myfield",
    mymethod : function(){
        return "hello";
// for-in loop
for (i in myObject) {
    console.log(i) //"field", "mymethod", "newMethod"

To avoid this inconvenient, we can use the method hasOwnProperty() which returns true if the property belongs to the object itself (not considering the prototype), so that:

Object.prototype.newMethod = "string";
// Object literal
var myObject = {
    field : "myfield",
    mymethod : function(){
        return "hello";
// for-in loop
for (i in myObject) {
        console.log(i) //"field", "mymethod"

In this case we get what we possibly were expecting!

In ECMAScript 5, few enhancements have been made and now you can define a property (Object.defineProperty method) and you can use the method Object.keys(obj) to return an array of the properties belonging to that object without the need of using the “dirty” hasOwnProperty(). That’s how you could rewrite the previous code in ECMAScript 5:

"use strict"
var myObject = {
    field : "myfield",
    mymethod : function(){
        return "hello";
Object.keys(myObject); //["field", "mymethod"]

Best way to loop through an Array in JavaScript

06/12/2010 § 4 Comments

Last week, a colleague of mine asked me “Why are you using a ‘standard for loop’ rather than the faster ‘for-in loop’ to loop through an Array in JavaScript?” and for this reason I’m going to write a short explanation about that.

First of all, when I talk about the standard “FOR loop“, I mean something like

for (var i=0; i < myArray.length; i++){}

instead the “FOR-IN loop” is something like:

for (var i in myArray){}

for-in loop is faster…just to type, for a lazy developer🙂 and it’s a common mistake especially for developers coming from Java programming (I’m a Java developer as well, that’s why I know that :P), trying to port Java into JavaScript.

The two main problems with for-in loop are :
1) It enumerates through all the properties even the ones associated to the Object (that can be augmented previously)
2) The order of the elements is not guaranteed.

You may not interested in the order of the elements(even if often you are), but you need to deal with the first issue and that’s what can happen:

var myArray = ["aa", "bb"];
// Object() augmented
Object.prototype.newMethod = "cc";
// for-in loop
for (var i in myArray) {
    console.log(myArray[i]); //"aa", bb", "cc"

The console will print not only the two elements from the array, but also the value of the new property in the Object. Remember that array are objects in JavaScript, at the root of the prototypal chain there is always Object and you never know if Object has augmented previously by a library or some script.

The correct way to execute that loop is using the for loop:

var myArray = ["aa", "bb"];
// Object() augmented
Object.prototype.newMethod = "cc";
//for loop
for (var i=0; i < myArray.length; i++) {
    console.log(myArray[i]); //"aa", bb"

Actually, we can make a micro-optimization to this, “caching” the length of the array and avoiding every time to calculate the length of the array.

var myArray = ["aa", "bb"];
for (var i=0, tot=myArray.length; i < tot; i++) {
    console.log(myArray[i]); //"aa", bb"

Notice that there is a comma between “var i=0” and “tot=myArray.length” as the “for loop” accepts three expressions.

If you find this last way a bit weird, you could do something like:

var myArray = ["aa", "bb"], i=0;
for (tot=myArray.length; i < tot; i++) {
    console.log(myArray[i]); //"aa", bb"

So it’s strongly recommended to use the FOR LOOP to loop through an Array and remember that Java and JavaScript are different.

In the next post, I may go through where the “for-in” loop is used.

Understanding WebStorage

22/11/2010 § 2 Comments

WebStorage is one the HTML5 features and it makes the browser capable to store information. Well, we have always been using Cookies, but they have few limitations and let’s see how WebStorage feature can fix these limitations.

Case 1: A user has two different windows opened and he wants to make two transactions on the same site. Using cookies, you could have “leaks” between windows and there is no clear distinction between the windows. WebStorage includes sessionStorage object and each window will have a different copy of this object, making each window being “independent”. As you can tell from the name this object is limited to a session, so as soon as you close your browser window, it will be erased.

Case 2: The site needs to keep information in common across multiple windows and even after the session is closed. Cookies are relative to each request so they can’t handle this case properly. WebStorage includes localStorage object and it’s relative to a specific domain and it lasts even after a session is finished.

Other thing, a cookie can have maximum size of 4Kb, Storage object can have size of 5Mb (quite standardized value in all browsers).

Reading the W3C specs, those are the methods for the Storage objects:

interface Storage {
    readonly attribute unsigned long length;
    getter DOMString key(in unsigned long index);
    getter any getItem(in DOMString key);
    setter creator void setItem(in DOMString key, in any value);
    deleter void removeItem(in DOMString key);
    void clear();

Let’s make some examples to understand better this methods:

localStorage.setItem("firstKey", "firstValue");
window.localStorage.getItem("firstKey"); //firstValue

This is really a basic use and show us how to use “setItem” and “getItem” methods. You can notice how you can use either “localStorage” or “window.localStorage”, this is because localStorage is attached to the window object. Also, the key/value are two strings, or better you can even set an object as value but you’d better “stringify” it (transforming it in a string using the stringify JSON method). Let’s see an example first trying to push an object in a Storage object without “stringify”:

localStorage.setItem("secondKey", {id : 1});
localStorage.getItem("secondKey"); // "[object Object]"

“[object Object]” is the String we get but we can’t get the real object. That’s how we can fix it:

localStorage.setItem("secondKey", JSON.stringify({id : 1}));
var a = JSON.parse(localStorage.getItem("secondKey")); // Object {id=1}
a.id; // 1

We used JSON stringify method and JSON parse method, that are useful to transform a JSON object in a string and viceversa. JSON object is now available in HTML5, but it’s not fully supported in all browsers, so you may want to download json.js written by Douglas Crockford, Yahoo JS Architect and in my opinion the maximum expert on JavaScript.

Let’s explore other methods available:

localStorage.length; // 1
localStorage.key(0); //"firstKey
localStorage.length; //0

they are quite straightforward methods: “removeItem(index)” will remove the key/value, “length” will return the number of key/value, “key(index)” will return the key for that index (0-based), “clear()” will remove all key/value.

Notice that I’ve been using localStorage in those example but I could use sessionStorage as well, as they share the same methods, coming from the same Interface.

You may meet another object called “globalStorage”, but remember that it’s been removed from the specs from Security reasons. It was basically holding different “localStorage” objects depending on the domain. So now “localStorage” for http://www.domain.com is different from “localStorage” for “a.domain.com” or “domain.com”.

Other feature is the “storage” event, which is triggered when the storage has change (using “setItem”, “clear”..). It has few attributes:
– key : key being changed
– oldValue : old value of the key before being changed
– newValue : new value of the key after being changed
– url : url of the document where the storage has been changed
– storageArea : storage object being changed (local or session)

Last thing, it’s supported in all modern browsers..and IE8! Suprising!

You wanna know more?
Have a read here (great writing from Mark Pilgrim) or have a look at the W3C Specs

Where Am I?

You are currently browsing entries tagged with JavaScript at Sebastiano Armeli's Tech Blog.


Get every new post delivered to your Inbox.