front-page.php

Toying With the HTML5 File System API | Nettuts+

An outstanding introduction to the HTML 5 File System API, from the folks at NetTuts+

Toying With the HTML5 File System API

Ivaylo Gerchev on Apr 11th 201

HTML5 provides us with a whole crop of new possibilities, such as drawing with canvas, implementing multimedia with the audio and video APIs, and so on. One of these tools, which is still relatively new, is the File System API. It gives us access to a sandboxed section of the user’s local file system, thus filling the gap between desktop and web applications even further! In today’s tutorial, we’ll go through the basics of this new and exciting API, exploring the most common filesystem tasks. Let’s get started!

via Toying With the HTML5 File System API | Nettuts+.

Getting Cozy With Underscore.js | Nettuts+

NetTuts+ has posted an new tutorial covering Underscore.js

Getting Cozy With Underscore.js

Siddharth on Mar 31st 2012

As JavaScript is slowly moving out of the browser, several tools have emerged that significantly improve JavaScript’s robustness.

One such tool is called Underscore.js and that’s what we’re going to take a. Let’s get started!ok at today…

See the full article: Getting Cozy With Underscore.js | Nettuts+.

Responsive Design: Off Canvas

Jason Weaver has posted an excellent discussion of a design pattern for responsive design that he labels “Off Canvas”.

Inspired by the observations of Luke Wroblewski, this Off Canvas layout demo has 3 panels that display differently depending on the viewport width. The idea here is to have the two supporting panels of navigation and sidebar content hidden just off-screen to the left and right for easy access on small/medium viewports.

See the Entire article here: Off Canvas.

Classical Inheritance in JavaScript

Notes for an upcoming discussion.

With some work, JavaScript can be used in an Object-Oriented design pattern similar to Java or C++. This can be a good thing, with programmers who are familiar with these languages moving to JavaScript for the first time. Setting aside the discussion on which inheritance pattern — prototypal or classical — is better JavaScript for now.

Class Definition

To define a class in JavaScript, create a function:


// a simple Product class
function Product(id, name) {
    this.id = id;
    this.name = name;
}

Product.prototype = {
    getName: function() {
        return this.name;
    }
}

With a little more work, we can create a class with private variables:


var Product = function(id, name) {
    var myId = id;
    this.name = name;
    this.getId = function() {
        return myId;
    }
}

Product.prototype = {
    getName: function() {
        return this.name;
    }
}

To use the class, it should be instantiated:

var myProduct = new Product('1', 'My cool widget');

myProduct.getId();   // "1"
myProduct.getName(); // "My cool widget";

The Product class inherits the prototype from Object. So methods from Object exist in the instance:

typeof myProduct.toString; // "function"

Note: this method for creating private variables can create larger objects. Every copy of Product gets a copy of the getId function, instead of accessing the prototype. If your Product Class is more complicated, or you needed to create a large number of copies of products, this might be a design issue to consider.

It is possible to change the prototype of a Class; all instance of the class receive the update immediately:

Product.prototype.getName = function() {
    return this.name.toUpperCase();
}

myProduct.getName(); // "MY COOL WIDGET"

It is possible to override methods from the prototype chain:

myProduct.hasOwnProperty('getName'); // false.. the instance inherits the method from the prototype.

myProduct.getName = function() {
    return this.name.toLowerCase();
}

myProduct.getName(); // "my cool widget"
myProduct.hasOwnProperty('getName'); // true.. the instance overrides the prototype.

This works up the chain as well:

myProduct.toString(); // "[object Object]"

Product.prototype.toString = function() {
    return this.name;
}

myProduct.toString(); // "My cool widget"

The new keyword, which was used to instantiate an instance of the class does several things.

  1. It creates a new empty object of type Object.
  2. it sets this new object’s internal, inaccessible, [[prototype]] (or __proto__) property to be the constructor function’s external, accessible, prototype object.
  3. It executes the constructor function, using the new object whenever ‘this’ is mentioned. If the constructor function returns a value, this is returned. Otherwise the new object is returned.

Classical Inheritance

Let us suppose that you have several different types of Products, and all of the different types of Products share some common attributes, and that all different types of products have some unique attributes that are not shared. It would be nice to keep all of the shared attributes in a base class, and create classes that inherit the base product’s attributes.

To create a class that inherits from the base Product Class several lines of code are needed. JavaScript does not have a extend keyword or any other built in method for creating inherited objects, so a bit of the work is done manually.

// assume a base Product Class already exists
var Widget = function(id, name, type) {
    Product.call(this, id, name);
    this.type = type || 'generic';
};

Widget.prototype = new Product(); // set the prototype chain
Widget.prototype.constructor = Widget; // constructor was reset above, set it back.

// Add methods unique to Widgets
Widget.prototype.getType = function() {
    return this.type;
};

var myWidget = new Widget('2', 'A Widget');
myWidget.getName(); // "A Widget"
myWidget.getType(); // "generic"

To cut down on the amount of typing, and to be more efficient, a simple function to extend one object (subclass) with a base class (superclass) can be created. In this function, a new empty function is created to avoid having to instantiate a potentially large super class object each time.

function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;
}

This does the same thing that we did manually in the example above. Use this extend function directly after declaring the constructor:

// assume a base Product object exists
var Widget = function(id, name, type) {
    Product.call(this, id, name);
    this.type = type;
}

extend(Widget, Product); 

Widget.prototype.getType = function() {
    return this.type;
}

This works, but our inherited class still calls the Product class directly. This tight coupling is undesirable, and can be avoided by alerting our extend helper function to extend one class (a subclass) from a base class (the superclass) and set the a reference to the superclass.

function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;

    // set a reference to the super class
    subClass.superclass = superClass.prototype;
    if (superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}

// Pro JavaScript Design Patterns: © 2008 Harmes/Diaz; apress

Now inherited classes have a convenient way to refer back to the superclass, which can be useful in methods that override the base class.

// assume the base Product Class and the extend function
var Widget = function(id, name, type) {
    Widget.superclass.constructor.call(this, id, name);
    this.type = type || 'generic';
}

extend(Widget, Product);

Widget.prototype.getName = function() {
    var name = Widget.superclass.getName.call(this);
    return name + ' (' + this.type + ')';
};

var myWidget = new Widget('2', 'a widget');
myWidget.getName();

Nettuts+ Promises Tutorial

A new tutorial posted on Nettuts with the most clear explanation of the Promises Design Pattern that I have encountered so far.

Understanding Promises

Trevor Burnham on Feb 22nd 2012

A Promise is an object that represents a one-time event, typically the outcome of an async task like an AJAX call. At first, a Promise is in a pending state. Eventually, it’s either resolved meaning the task is done or rejected if the task failed. Once a Promise is resolved or rejected, it’ll remain in that state forever, and its callbacks will never fire again.

You can attach callbacks to the Promise, which will fire when the Promise is resolved or rejected. And you can add more callbacks whenever you want – even after the Promise has been resolved/rejected! In that case, they’ll fire immediately.

Plus, you can combine Promises logically into new Promises. That makes it trivially easy to write code that says, “When all of these things have happened, do this other thing.”

see the whole article at Wrangle Async Tasks with jQuery Promises | Nettuts+.

JavaScript Prototypal Inheritance

In this example of prototypal inheritance, we are creating a Bug prototype. It serves as a base to provide properties and methods that all bugs share. Then we will instantiate new instances of the Bug prototype for specific implementations.

var clone = function(o) {
    function F(){}
    F.prototype = o;
    return new F;
};

// Our insect prototype
var Bug = {
    species: "Prototype Bug",
    attributes: [
        'Three Body Segments',
        'Six Legs',
        'Exo-Sekelton'
    ],
    getSpecies: function() {
        return this.species;
    }
};

var beetle = clone(Bug);
beetle.species = 'Beetle';
beetle.attributes.push('Eats Dung');

// we now have a child of the prototype with additional attributes.
console.log(beetle);

// The prototype
var ladyBug = clone(Bug);
ladyBug.species = 'Japanese Bug';
console.log(ladyBug);

The problem here is that the ladyBug object gets the attribute ‘Eats Dung’, because beetle actually modified a reference to the attributes in the prototype, not its own copy. This will trip up programmers that are used to a classical inheritance model.

The solution is to create factory functions to provide these properties and methods.

var Bug = {
    getSpecies: function() {
        return this.species;
    }
};
Bug.species = 'default species';
Bug.addBugAttributes = function() {
    var attr = ['three body segments', 'six legs', 'compound eyes'];
    return attr;
};
Bug.attributes = Bug.addBugAttributes();

var beetle = clone(Bug);
beetle.species = 'Beetle';
beetle.attributes = Bug.addBugAttributes();
beetle.attributes.push('Eats Dung');

var ladyBug = clone(Bug);
ladyBug.species = 'Japanese Beetle';
ladyBug.attributes = Bug.addBugAttributes();
ladyBug.attributes.push('Eats Aphids');

console.log(ladyBug);
console.log(beetle);

Bricss – Simple responsive design test page

I was completely excited when I saw this post. A responsive design test page. Make sure to check out the links at the end of the article to the bookmarklets that have been generated around this idea.

Very handy little tool that will be part of my tool kit going forward.

Bricss – Simple responsive design test page.

Primitives vs. Constructed Objects in JavaScript

A user asked me a question in a recent training session.

Can you use a constructor to create primitives?

In other words:

var x = new Boolean(false);

I thought about it, and answered, “Sure. But why?” I mean, we aren’t programming in Java here. This type of constructor is also dangerous.

// Don't do this in production
var maybeAlertUser = new Boolean(false);

(maybeAlertUser  === true); // this is false, but ...

if (maybeAlertUser) {
    // this always alerts
    alert("Houston, we have a problem");
}

alert(typeof maybeAlertUser); // object

We discussed that it is safe to use the object to type cast:

var x = 0;
var maybeAlertUser = Boolean(x);

if (maybeAlertUser) {
    // this never alerts
    alert("Houston, we have a problem");
}

(maybeAlertUser === false); // yup!

The JavaScript idiom to use negation operator seems to be just as safe. In this instance, the first operation converts zero to a boolean and inverts the value (turning it to true). And the second inverts the value (turning it to false), but it strikes terror into Java coders.

var x = 0;
var maybeAlertUser = !! x;

if (maybeAlertUser) {
    alert("Houston, we have a problem"); // never alerts
}

(maybeAlertUser === false); // yup!

Which do you prefer?

HTML5 and You | Nettuts+

NetTuts has an outstanding collection of HTML 5 Tutorials organized into a 14-article Session:

HTML5 has been the buzzword with the web development community for a while now. If you feel a bit overwhelmed and behind the pack, never fear. This session is all you need to get up to speed, fast. We cover everything from the new HTML5 elements, to microdata, to the new JavaScript APIs.

See the full article: HTML5 and You | Nettuts+.

Test-Driven JavaScript Development in Practice | Nettuts+

I ran across this tutorial which was originally posted in November of 2012. Recently, I gave a demonstration of qunit in our technology discussion group, so the timing is right on.

Test-Driven JavaScript Development in Practice

Christian Johansen on Jan 14th 2012

Tutorial Details

  • Topic: JavaScript Testing
  • Difficulty: Intermediate-Advanced

TDD is an iterative development process where each iteration starts by writing a test which forms a part of the specification we are implementing. The short iterations allow for more instant feedback on the code we are writing, and bad design decisions are easier to catch. By writing the tests prior to any production code, good unit test coverage comes with the territory, but that is merely a welcome side-effect.

See the full article:  Test-Driven JavaScript Development in Practice | Nettuts+.