front-page.php

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+.

Links

Some links from a recent discussion.

Zurb grid boiler plates
http://foundation.zurb.com/

Nettuts : web tutorials
http://www.nettuts.com

CSS Tips and Tricks
http://css-tricks.com/

Encapsulation in JavaScript

Some Notes from a discussion of encapsulation in JavaScript

The topic of encapsulation in JavaScript came up in our bi-weekly technologists group recently. First question was, what is encapsulation and why is it a good thing. The first obvious benefit is the elimination of global values.

An example with global variables. TAX_RATE is vulnerable; it is a global variable that can be overwritten.

// Not Best Practice. Relies on Global variables and functions.
var TAX_RATE = 0.07;

function calculateTotalPrice(basePrice) {
    return basePrice + (basePrice * TAX_RATE);
}

function calcPrice () {
    var basePrice = document.getElementById('ex1_basePrice').value;
    basePrice = basePrice - 0; // cast to integer
    var totalPrice = calculateTotalPrice(basePrice);
    document.getElementById('ex1_totalPrice').value = totalPrice;
}

The problem with the global variable, or course, is that anything can come along a modify it. In this HTML example, click Calculate Price. Then open a console window (Use Firebug or Developer Tools) and alter this global variable:

> TAX_RATE = 1.00;

Now click Calculate Price. It would be just as easy to overwrite the global functions to produce different values:

> calcPrice = function() { return 1; }

Now our price calculation is completely re-written.

One practice to prevent the collision of global variables is to organize them in a single global variable:

var myApp = {
    TAX_RATE: 0.08,
     
    calculateTotalPrice: function(basePrice) {
        return basePrice + (basePrice * this.TAX_RATE);
    },
     
    calcPrice: function() {
        var basePrice = document.getElementById('ex3_basePrice').value;
        basePrice = basePrice - 0;
        var totalPrice = myApp.calculateTotalPrice(basePrice);
        document.getElementById('ex3_totalPrice').value = totalPrice;
    }
};

This works, but it can still leave myApp vulnerable. myApp.TAX_RATE is still globally accessible.

Using encapsulation, it is possible to create protected members.

var calcPrice2 = (function() {
    // private
    var PRIVATE_TAX_RATE = 0.05;

    function calculateTotalPrice2(basePrice) {
        return basePrice + (basePrice * PRIVATE_TAX_RATE);
    }

    // public
    return function() {
        var basePrice = document.getElementById('ex2_basePrice').value;
        basePrice = basePrice - 0;
        var totalPrice = calculateTotalPrice2(basePrice);
        document.getElementById('ex2_totalPrice').value = totalPrice;
    };
})();

Custom exception handling in JavaScript

A co-worker showed me a neat trick today. Many of you have no doubt seen it, but I thought I would use it in a discussion about custom exception handling in JavaScript. I was buried in some Java Coding, so the topic was fresh.

The trick:

Math.max.apply(Math, array);

Awesome. It returns the highest value in the array.

What happens if a member of array can’t be parsed as a Number? It returns NaN. Which is great, but I wondered if I can wrap that in a try/catch block and catch NaN. Not exactly, but I can come close.

The try/catch/finally mechanism isn’t exactly new in JavaScript, but it is, In my opinion, under-utilized. Mostly, developers use it to protect code from errors. Consider:

var foo;

try {
    foo.undefinedFunction("bar");
} catch (ex) {
    console.log(ex);
}

alert("the error didn't stop me.");

In this example, the try catch is used instead of the traditional if (typeof foo.undefinedFunction !== “undefined”) .

But it is possible with JavaScript keyword throw to implement exception handling.

function getMaxValueOfArray(ar) /* throws illegal argument error, NaN error */ {
    var n;
    if (ar instanceof Array) {
        if (isNaN(n = Math.max.apply(Math, ar))) {
            throw new Error("NaN error. The first argument to getMax must be an array of Numbers");
        }

        return n;
    } else {
        throw new Error("illegal Argument. The first argument to getMax must be an instance of Array");
    }
}

var max;
try {
   max = getMaxValueOfArray('1');
} catch (ex) {
  alert(ex);
}

try {
    max = getMaxValueOfArray([1, 'foo', 2]);
} catch(ex) {
   alert(ex);
}

try {
     max = getMaxValueOfArray([1, 4, 2]);
} catch(ex) {
     alert(ex);
}

max;

We can extend the practice and add some more debugging information for FireFox with a custom function:


function CustomError(errorName, errorMessage) {
   var error = new Error();
   error.name = errorName;
   error.message = errorMessage;

// For FireFox at least, there is property called stack to hold the stack trace.
   if (typeof error.stack !== "undefined") {
      var errorstack = error.stack.split(/\s*(@|at)\s*/);
      errorstack = errorstack[errorstack.length - 1]
                   .replace(/^\s+|\s+$/g, '')
                   .split(/\:([0-9]+)/);
      error.fileName = errorstack[0];
      error.lineNumber = errorstack[1];
   }
   return error;
}

function getMaxValueOfArray(ar) /* throws illegal argument error, NaN error */ {
    var n;
    if (ar instanceof Array) {
        if (isNaN(n = Math.max.apply(Math, ar))) {
            throw new CustomError("NaN Error", "The first argument to getMax must be an array of Numbers");
        }

        return n;
    } else {
        throw new CustomError("illegalArgument Error", "The first argument to getMax must be an instance of Array");
    }
}

var max;
try {
   max = getMaxValueOfArray('1');
} catch (ex) {
   ex.stack ? alert(ex.stack) : alert(ex);
}

try {
    max = getMaxValueOfArray([1, 'foo', 2]);
} catch(ex) {
    ex.stack ? alert(ex.stack) : alert(ex);
}

try {
     max = getMaxValueOfArray([1, 4, 2]);
} catch(ex) {
     ex.stack ? alert(ex.stack) : alert(ex);
}

Further reading: http://www.sitepoint.com/throwing-better-errors-using-stack/

Understanding Prototypal Inheritance in JavaScript | LakTEK

A good basic description of the Prototypal Inheritance in JavaScript:

Understanding Prototypal Inheritance in JavaScript

02 February 2011

Behavior reuse is one of the key aspects of Object Oriented programming. Many mainstream Object Oriented languages, achieves behavior reuse by using class based inheritance. In class based inheritance, a class defines how objects stemming from it should behave.

However, not all languages use class based inheritance to achieve behavior reuse. The best possible example is JavaScript. It doesn’t have a concept of classes. Some people often confused about JavaScript’s object oriented capabilities due to this fact. But in reality, JavaScript is a more expressive and flexible Object Oriented language compared to some of the mainstream languages.

If JavaScript doesn’t have class based inheritance, how does it reuse the behavior? For that it follows the technique called Prototypal Inheritance.

See the Full Article: Understanding Prototypal Inheritance in JavaScript | LakTEK.

An In Depth Overview of HTML5 Multimedia and Accessibility | Nettuts+

An In Depth Overview of HTML5 Multimedia and Accessibility | Nettuts+.

Ian Devlin on Jan 4th 2012

Tutorial Details
  • Topic: HTML5 Media
  • Difficulty: Moderate

In this tutorial, you’ll learn how HTML5 helps to provide you with several ways of presenting your media content to users. As a result, you’ll increase the availability of your media to users with different needs and requirements, making it more accessible.

 

Wrangling with the Facebook Graph API | Nettuts+

Wrangling with the Facebook Graph API

Nikko Bautista on Dec 1st 2011

Tutorial Details

Topic: Facebook Graph API

Version: Facebook PHP SDK v.3.1.1

 

Have you ever wanted to learn how to make your applications more social with Facebook? It’s much easier than you think!

In this tutorial, we’ll be building an application that reads and publishes data to and from Facebook using Facebook’s Graph API. Interested? Join me after the jump!

via Wrangling with the Facebook Graph API | Nettuts+.