Facebook Access Token


When you need to create a customized Facebook Newsfeed on your web site, you can avoid using the common iFrame approach and create a widget using JSON format response from Facebook’s RESTful API. In order to get data from the Facebook API, there are several steps in the process. Since Facebook switched to OAuth 2.0 authentication, user data is a lot more secure. As a result, before any app can display user data it needs to have right permissions granted by the user. In this scenario, you the application developer must have Facebook account with a newsfeed which you want to customize for your web site
There are two types of Facebook access tokens

  1. Temporary Access token – valid for 1 hour
  2. Long-lived Access token – valid for 60 days

How to obtain a long-lived access token
Before you can generate the long-lived access token, first you have to generate the temporary access token, then use it to get the long-lived version before it expires. The steps are:

  • Create a Facebook developer account: from your regular account click on “Developers” link in the footer and register. You should get an email to confirm registration.
  • Log into your account and click on the “Developers” link.
  • Click “Tools” in the top menu, then “Graph API Explorer” link – gives screen below

Facebook Graph API Explorer

  • In the GET text field enter your account number/accounts (the account number should be there by default)
  • Click “Get Access Token” button
  • On the pop up window go to “Extended Permissions” and check “manage_pages” (see screenshot below)

Facebook Access Token screen 2

  • Click “Get Access Token”
  • Click “Submit” and the access token will be generated (highlighted in screenshot below)

Facebook Access Token screen 3

Generating a long-lived Facebook Access Token

After you have obtained a temporary token by following the steps above, you can then generate the long lived token. Click here for more information.

  • Create a Facebook web app, click on the “Apps” link and then “+ Create New App” button

Facebook Access Token screen 4

  • Click the “App on Facebook” option and enter URL where the app will be saved on your public domain: App Domains and Canvas URL options are required

Facebook Access Token screen 5

  • Enter the parameters or strings lines 2 to 5 in the following PHP script
 <?php
$app_id = "349541638510298";
 $app_secret = "fd1cc68929ff995f9dc6799518a0cbb5";
$my_url = "http://apps.facebook.com/ra_social_feed";    // known valid access token stored in a database
$access_token = "CAAE96AEyltoBAOZBHa676Hlxuleiqnc7xbzwkEvkBYszcsd5oxZA4jLSJd2RPonZAHVF02sP3UfBF5FQTVXpxWHC9Tl3yvixxUCSgDsxH0yZC0wlLgOUyEiM9ZCpok9FZBhjGH3bDoUw4vFFe24dZCta5ozSBtBkuzINrtRZCPfgdVBrHI40CmlqYo6qpvE8kZCYZD";
$code = $_REQUEST["code"];    // If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {     $token_url="https://graph.facebook.com/oauth/access_token?client_id="
 . $app_id . "&redirect_uri=" . urlencode($my_url)
 . "&client_secret=" . $app_secret . "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);    //Check for errors
 if ($decoded_response->error) {
 // check to see if this is an oAuth error:
 if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
 $dialog_url= "https://www.facebook.com/dialog/oauth?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
  }
else {       echo "other error has happened";
 }
}
else {
 // success
echo("successhello" . $decoded_response->name);
echo($code);   }
// note this wrapper function exists in order to circumvent PHP’s
 //strict obeying of HTTP error codes.  In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
 $c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);     if ($contents) return $contents;
else return FALSE;   }
?>


  • Logout of your Facebook account after creating the app, before running the PHP script in your browser
  • The above script will redirect you to a URL like the one below on the browser
    https://graph.facebook.com/oauth/access_token?code=…
  • Get the string (should be something like this: AQCn41Svv5DbWrnFY0Wf.....YbNm_yz2rE#_ ) after code= and paste it on the code= URL below and RUN the URL below on the browser. (Also insert your App_Id and and App_Secret in the URL)
  • https://graph.facebook.com/oauth/access_token?client_id=App_Id
    &redirect_uri=http://apps.facebook.com/poemsoflove
    &client_secret=App_Secret
    &code=AQCn41Svv5DbWrnFY0Wf.....YbNm_yz2rE#_&display=popup
  • You will get the following response with the 60 day access token

    access_token=<Long_Lived_Access_Token>&expires=5180130
Posted in Media, Tutorials, Web design & development | Leave a comment

Immediate functions


Immediate functions

These are self-invoking functions, i.e functions that initialize themselves.
The general syntax looks like this:

(function() {
// do stuff here
})();

In the above code, the function operator (), in line 3, applies to the whole anonymous function, which is also enclosed in a set of parenthesis (...). So the anonymous function is being used like an expression just like common mathematical expressions: (6 + 2)*5 and 6 + (2*5). The parenthesis contain an expression that must be resolved first before applying the * or + operators respectively.

This technique is extremely useful in advanced JavaScript and is employed in most JavaScript libraries ranging from jQuery to Prototype. A single expression performs three main tasks:

  1. It creates an instance of the anonymous function
  2. It invokes the anonymous function
  3. It removes all references to the anonymous function at the end of the statement

It’s important to note that the anonymous function creates a closure or self-contained scope.

Simulated access control

Immediate functions can be used to create OOP-like features in JavaScript. Self-contained scopes help to make modular constructs as well as private variables, possible. The snippet below illustrates an example.

(function() {
   var clickCount = 0;
   document.addEventListener("click", function(){
      alert(++clickCount);
   ), false);
})();

Since the anonymous or immediate function is invoked as soon as the script is launched, the click event handler is bound at the same time. This handler is within the same closure as the clickCount variable. As a result, clickCount acts like a private variable for the event handler. It can only be referenced within the self-contained scope of the anonymous function.

In the example above, the immediate function had no arguments or parameters. There are several very important practical applications for this technique. The most common is perhaps with the jQuery $ alias, which is also used by other libraries such as Prototype. When using two libraries that have the same alias, you can avoid name space conflicts by adding a parameter to the immediate function.

<body>
<input type="button" value="click" />
<script type="text/javascript">
  $ = function(){ alert ('$ is not jQuery!'); };
  (function($){
     $('input').on('click', function(e){
        $(e.target).addClass('btnclick');
      })

  })(jQuery);
</script>
</body>

run the code

Looping with immediate functions

Closures and loops require special attention in order to avoid common pitfalls. For example in the code below, the result is not what you might expect.

<body>
    <ul>
       <li>first item</li>
       <li>second item</li>
       <li>third item</li>
   </ul>
<script type="text/javascript">
    var items = document.getElementsByTagName("li");
    for(var i = 0; i < items.length; i++) {
      items[i].addEventListener("click", function() {
      alert("item # " + i + " was clicked");
      }, false);
    }
</script>
</body>

run the code
As you can see in the above code, the alert always points to the last item in the list. This happens because the closure references the enclosed variables and the last value over rides all previous values. There’s a simple solution to this problem using another immediate function but passing a parameter as the function’s argument as shown below:

<body>
    <ul>
       <li>first item</li>
       <li>second item</li>
       <li>third item</li>
   </ul>
<script type="text/javascript">
    var items = document.getElementsByTagName("li");
    for(var i = 0; i < items.length; i++) (function(count){
      items[i].addEventListener("click", function() {
      alert("item #" + count + " was clicked");
      }, false);
    })(count);
</script>
</body>

run the code

The body of the previous for loop has been replaced by the immediate function. Each time the loop runs the value of the counter is passed as the argument of the new immediate function, as result each loop has a different value. This value is then passed onto the alert, which is within the scope of the new immediate function.

Posted in Code, Tutorials, Web design & development | Leave a comment

Memoization and Currying – the secret sauce


JavaScript Secrets

Currying

Currying sounds like some secret sauce, however the name is derived from Haskell Brooks Curry, the American Mathematician (1900 – 1982).
This technique involves predefining a function, with a partial list of arguments using a sort of “proxy function”. Whenever you have to call the same function several times, using some of the arguments repeatedly, then Currying can be used to avoid repeated calls to the same function. The following snippet shows a general purpose Currying function.

Function.prototype.partial = function(){
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
     var arg = 0;
        for (var i = 0; i < args.length && arg < arguments.length; i++) {
            if (args[i] === undefined) {
             args[i] = arguments[arg++];
            }
        }
        return fn.apply(this, args);
    };
};

String.prototype.csv = String.prototype.split.partial(/,\s*/);
var results = ("Dock, Cruise, Pier").csv();
if(results[0] == "Dock" && results[1] == "Cruise" && results[2] == "Pier"){
   alert("The string was split as expected");
}

run the code

Memoization

Memoization is a technique that is often used to improve the performance of JavaScript functions, by storing precomputed values in a function’s property or cache. In this example, isPrime() is an immediate function that gets memoize() method applied to it. This method wraps the memoized() method around the original isPrime() function through a closure. So we end up with a chain of functions: isPrime() => memoize() => memoized().

Function.prototype.memoized = function(key){
    this._values = this._values || {};
    return this._values[key] !== undefined ?
        this._values[key] :
    this._values[key] = this.apply(this, arguments);

};

Function.prototype.memoize = function(){
  var fn = this;
    return function(){
      return fn.memoized.apply( fn, arguments );
    };
};

var isPrime = (function(num){
 var prime = num != 1;
    for (var i = 2; i < num; i++){
        if (num % i == 0){
            prime = false;
            break;
        }
    }
    return prime;
}).memoize();

if (isPrime(23)){
 alert ("23 is a prime number");
}

run the code

Function wrapping

The example below shows how the Prototype JavaScript library uses function wrapping to resolve a cross-browser issue with Opera’s implementation of accessing HTML title attributes. At first the code looks like a riddle wrapped in mystery, inside an enigma. Several things are happening in just a few lines of code. The wrap() function takes three arguments:

  1. the object whose method is being wrapped,
  2. then the method to be wrapped,
  3. and finally the wrapping function.

Next we use the same technique used for memoization in the previous example to wrap the wrapper function around object[method] lines 2 – 6. In this case using apply() with object[] as context, and creating an arguments list by concatinating the original arguments with the method being wrapped. Effectively, object[method] now executes the wrapper function (via apply()). Note that the wrapper function has not being explicitly defined yet, it’s created when you use the wrap function in line 19. The apply() method is used to give the wrapper function its context and arguments list using the bind() method created in line 10. If you find this technique hard to digest, you are not alone. It may take a while to wrap your head around it (pun intended).

function wrap(object, method, wrapper) {
 var fn = object[method];
    return object[method] = funtion(){
                   return wrapper.apply(this, [fn.bind(this)].concat(
                       Arry.prototype.slice.call(arguments)));
                   };

}

Function.prototype.bind = function(){
 var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
    return function(){
     return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
    }
}

if (Prototype.Browser.Opera) {
 wrap(Element.Methods, "readAttribute",
      function(original, elem, attr){
      return attr == "title" ?
          elem.title :
      original(elem, attr);
      });
}

run the code

Posted in Code, Tutorials, Web design & development | Leave a comment

Closures – closely guarded secrets


JavaScript Secrets

Inside a closure

As briefly described in the previous post, a closure is the scope that is created when a function is able to access variables that are defined outside the function. Normally a function only has access to variables defined within it’s own body. The following code sample illustrates this:

var externalVar = "port";
var sail;

function harbour (){
   var internalVar = "dock";

   function quay () {
      if(externalVar){
      alert("I can see the port");
      }
      if(internalVar){
      alert("I can see the dock");
      }

   }
   sail = quay;

  }
   harbour();

   sail();

run the code

Animation with Closures

In the example below, one anonymous function is used to access three variables (tick, elem and timer) in order to animate the div element. The function maintains reference to these variables throughout the setInterval loop. As a result the variables should not be in global scope where other objects could interfere and cause a conflict.

<!doctype html>
   <head>
      <title>Animation with Closures</title>
	  <style>
	   #ship{
	      width: 120px;
		  height: 120px;
		  background-color: red;
		  position: relative;
	   }
	  </style>
   </head>
   <body>
   <div id="ship">Sailing</div>
   <script type="text/javascript">
      function animateShip(elemId){
         var elem = document.getElementById(elemId);
         var tick = 0;

         var timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);
               if(tick == 120) {
               alert("Tick was accessed via a closure");
               }
               if(elem && timer) {
               alert("Element elem and timer also accessed via a closure");
              }

           }
         }, 10);
     }
   animateShip("ship");
   </script>

   </body>
</html>

run the code
It should be noted that the previous example would still work even the variables were defined in global scope, outside the animateShip() function. This is shown in the next example:

<!doctype html>
   <head>
      <title>Animation with Closures</title>
	  <style>
	  #ship {
            width: 150px;
            height: 70px;
            background-color: #fdd;
            color: #fff;
            text-align: center;
            font-size: 18px;
            position: relative;
        }
	  </style>
   </head>
   <body>
   <div id="ship">Sailing</div>
   <script type="text/javascript">
      var tick = 0;
      var elem;
      var timer;
      function animateShip(elemId){
         elem = document.getElementById(elemId);

         timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);
               if(tick == 120) {
               alert("Tick was accessed via a closure");
               }
               if(elem && timer) {
               alert("Element elem and timer also accessed via a closure");
              }

           }
         }, 10);
     }
   animateShip("ship");
   </script>

   </body>
</html>

run the code
However when you try to animate two or more elements with this setup, as shown below, a serious problem arises. Only the last element gets animated, because it over writes all previous instances of the variables.

<!doctype html>
   <head>
      <title>Animation with Closures</title>
      <style>
         #ship {
         width: 150px;
         height: 70px;
         background-color: #fdd;
         color: #fff;
         text-align: center;
         font-size: 18px;
         position: relative;
        }
        #ship2 {
        width: 150px;
        height: 70px;
        background-color: orange;
        color: #fff;
        text-align: center;
        font-size: 18px;
        position: relative;
        left: 150px;
        }
   </style>
   </head>
   <body>
   <div id="ship">Sailing ship1</div>
   <div id="ship2">Sailing ship2</div>
   <script type="text/javascript">
      var tick = 0;
      var elem;
      var timer;
      function animateShip(elemId){
         elem = document.getElementById(elemId);

         timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);

           }
         }, 10);
     }
   animateShip("ship");
   animateShip("ship2");
   </script>

   </body>
</html>

run the code
When we restore the variables to the initial scope within the animateShip() function, then both divs are animated simultaneously. This insightful example shows the real power of closures.It’s sort of an Aha! moment in the JavaScript closure ecosystem. Imagine creating multiple animations in a complex application, for example an accordion with several items; All the items can be animated by a single jQuery object. You can now understand why the concept of closures is so important in object oriented JavaScript. Libraries like jQuery, Backbone, Knockout and Ember could not exist without closures.

<!doctype html>
   <head>
      <title>Animation with Closures</title>
      <style>
	   #ship {
         width: 150px;
         height: 70px;
         background-color: #fdd;
         color: #fff;
         text-align: center;
         font-size: 18px;
         position: relative;
        }
        #ship2 {
        width: 150px;
        height: 70px;
        background-color: orange;
        color: #fff;
        text-align: center;
        font-size: 18px;
        position: relative;
        left: 150px;
        }
   </style>
   </head>
   <body>
   <div id="ship">Sailing</div>
   <script type="text/javascript">

      function animateShip(elemId){
         var tick = 0;
         var elem = document.getElementById(elemId);

         var timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);

           }
         }, 10);
     }
   animateShip("ship");
   animateShip("ship2");
   </script>

   </body>
</html>

run the code

Binding a function’s context

In the code sample below, shows how a functions context can be forced to have a certain value. The bind() function has a closure within which an anonymous function is being used to change the context of another method. The code is rather convoluted and needs to be untangled. This technique is being used to resolve the problem caused the browsers default behaviour of assigning the context of a click event to the button element that was clicked. Here, the context has been switched to the myButton object.

<html>
   <head><title>Binding context</title></head>
   <body>
   <button id="btn">Click here</button>
<script type="text/javascript">
   function bind(context, name){
     return function(){
       return context[name].apply(context, arguments);
     };
   }

var myButton = {
    clicked: false,
    click:  function (){
      this.clicked = true;
      if(myButton.clicked){
      alert("You clicked myButton!" + "in this context " + this);
      }

      }
    };

var el = document.getElementById("btn");
el.addEventListener("click", bind(myButton, "click"), false);
</script>
</html>

run the code

Binding function context in JavaScript

Posted in Code, Tutorials, Web design & development | Leave a comment

Elements of Arguments in JavaScript Functions


Variable length argument lists

JavaScript functions can accept variable length argument lists. By taking advantage of this powerful feature, developers have greater control over how functions are defined and invoked. This post will discuss:

  • How to insert variable number of arguments into a function
  • How JavaScript can implement function overloading
  • The length property of argument lists

First let’s look at how the apply() method can be used in this situation. Suppose you need to find out the largest or smallest number in an Array. JavaScript has no built in function that can perform this simple task. Even though the Math object has min() and max() methods neither one accepts an Array as the argument list. That’s amazing but true. Fortunately there is a work around for this problem shown in the code below:

function minimum(array){
   return Math.min.apply(Math, array);
}

function maximum (array) {
   return Math.max.apply(Math, array);
}

myArray = [3, 6, 7, 12, 2, 8];

if(minimum(myArray) == 2){
   alert("Found the smallest number");
}

if(maximum(myArray) == 12){
   alert("Found the largest number");
}

run the code

Function overloading

The key to variable arguments list is the arguments parameter, which all JavaScript functions possess.
It provides access to all passed arguments in a function even if not all have been defined when the function was created.
In other object oriented languages like Java, method overloading is implemented by defining separate methods for each possible argument list. However in JavaScript, there is only one function definition which can then be invoked with various argument lists.
The code sample below illustrates how to merge the properties of several objects into one root object. The initial function definition has one argument, this corresponds to the {name: "Titanic"} object at initialization. After looping through the parameters list, the object becomes {name: "Titanic", port: "Pier 24", company: "Disney"}

  function merge(root){
	for (var i = 1; i < arguments.length; i++){
		for (var key in arguments[i]) {
			root[key] = arguments[i][key];
		}
	}
	return root;
}

var merged = merge (
	{name: "Titanic"},
	{port: "Pearl Harbour"},
	{company: "Disney"}

);

if(merged.name =="Titanic"){alert("The name is still the same")};
if(merged.port == "Pearl Harbour") {alert("The port has been moved over")};
if(merged.company == "Disney") {alert("The company has also been moved over")};

run the code

You can find examples in JavaScript libraries such as jQuery, the animate() function below accepts one object argument in the first case and two in the second:

// animate() takes one object, an integer and a function as arguments
 $('#port').animate({
   opacity: 0.25,
   left: '+=50',
   height: 'toggle'
   }, 5000, function() {
   // Animation complete.
   });

// here animate() takes two objects and a method as arguments
 $('#port').animate({
   width: 'toggle',
   height: 'toggle'
   }, {
   duration: 5000,
   specialEasing: {
     width: 'linear',
     height: 'easeOutBounce'
   },
   complete: function() {
     $(this).after('<div>The Easing Animation is complete.</div>');
   }
});

Functions also have a length property, similar to the arguments parameter’s length property. The function length property has a value equal to the number of items in the arguments list when the function is invoked. Whereas the arguments length property is the number of items when the function is defined. These two values may be equal except when you have function overloading.

The code sample below illustrates a simple function overloading example. Here we three methods with the same name – find bound to a base object. The three methods accept different number of arguments. The first accepts no argument, while the second accepts one argument, and the third accepts two arguments.

One important fact is that these methods are referenced from within closures. A closure is created when a function is able to access variables that are defined outside its normal scope. This topic will be discussed further in the next post.

Even though function overloading is a powerful technique, this example has some fundamental weaknesses. It only works for functions with different arguments length, and does not differentiate between argument type or name. Since the functions all have the same name, there’s a function call overhead that could affect performance.

run the code

   	function addMethod(object, name, fn){
	var old = object[name];

	object[name] = function(){
		if(fn.length == arguments.length){
			return fn.apply(this, arguments)}
			else if (typeof old == 'function')
			return old.apply(this, arguments);
		};
}

var ninjas = {
	values: ["Abraham Lincoln", "George Washington", "Charles Drew"]
};

addMethod(ninjas, "find", function(){
	return this.values;
});

addMethod(ninjas, "find", function(name){
	var ret =[];
	for(var i = 0; i < this.values.length; i++)
	if(this.values[i].indexOf(name) == 0)
	ret.push(this.values[i]);
	return ret;
});

addMethod(ninjas, "find" , function(first, last){
	var ret =[];
	for  (var  i = 0; i <this.values.length; i++)
		if (this.values[i] == (first + " " + last))
		ret.push(this.values[i])
		return ret;
});

if(ninjas.find().length == 3){ alert("Found all Ninjas")};

if(ninjas.find("George").length == 1){alert("Found Ninja by first name")};

if(ninjas.find("Abraham", "Lincoln").length == 1){alert("Found Ninja by first  and last name")};
Posted in Code, Tutorials, Web design & development | Leave a comment

Even More JavaScript Secrets


This post will focus on exploiting the similarities between functions and objects. Just as you can attach properties to objects, functions can also have properties attached.

   var myObj = {};
   var myFn = function() {};
   myObj.prop = "ship (cruise)";
   myFn.prop = "frigate (mission)";

Event callback management is one of several uses for this aspect of functions. In the following code sample by using the function’d id property fn.id we can add the frigate function to the shipyard object’s dock.

var shipyard = {
  pierId: 1,

  dock: {},

  add: function(fn) {
         if(!fn.id) {
            fn.id = shipyard.pierId++;
            return !!(shipyard.dock[fn.id] = fn); // the !! returns the Boolean value of any JavaScript expression
         }
    }

}

function frigate() {};
if(shipyard.add(frigate)){
  alert("frigate was added to shipyard");

 if(!shipyard.add(frigate)){
  alert("frigate was added once");
}
}

Memoization

This technique is used to store processor intensive calculated values. It makes your code much more efficient, especially when the same calculation is repeated several times. One common application is to store DOM elements by tag name.

function isPrimeNbr(val) {
   if(!isPrimeNbr.answers) isPrimeNbr = {};
if(isPrimeNbr.asnwers[val] != null) {
     return isPrimeNbr.answers[val];
     }
   var prime = val != 1;
for( var i = 2; i < val; i++) {
    if (val % i == 0) {
    prime = false;
    break
}
}
return isPrimeNbr.answers[val] = prime;
}
if(isPrimeNbr(57){
  alert("57 is a prime number");
}
if(isPrimeNbr.answers[57]){
 alert("The answer was safely cached");
}

The code below shows an example of memoizing DOM elements by tag name. The downside of this is memory that gets tied down, the improved performance compensates for this. Also some may argue that caching should not be performed by functions meant for business logic in order to keep separation of tasks intact.

function getElements(name){
   if (!getElements.cache) getElements.cache = {}
return getElements.cache[name] = getElements.cache[name] || document.getElementByTagName(name);
}

Array methods

Javascript Arrays are also Objects and this commonality can be used to create some interesting techniques. In situations where an Object contains a collection of data and also needs to store certain metadata concerning the data collection. Simply creating a new Object each time we need different metadata properties would be inefficient and time consuming. The example below shows how you can create an Object and then apply existing Array methods to it.

<body>
<input id="ying" />
<input id="yang" />
<script type="text/javascript">
var elems = {
    length:0,

    add: function(elem) {
         Array.prototype.push.call(this, elem);
    },

    gather: function(id) {
    this.add(document.getElementById(id));
    }
};

elems.gather("ying");
if(elems.length == 1 && elems[0].nodeType){
  alert("Verify that there's an element in our store");
}

elems.gather("yang");
if(elems.length == 2 && elems[0].nodeType){
  alert("Verified that Ying has got a Yang");
}
</script>

</body>

The code sample above shows a conventional object elems that has been set up to behave like an array. First it has a length property. It also has a method add() that inserts new elements, this method is implemented using Array.prototype.push. Normally, the context of Array.prototype.push is the array itself, however in this case by using the call() method the context is defined as the elems object. By so doing the length property is also incremented as in a regular array. The gather() method is more of a helper function that retrieves the DOM elements by id and invokes the add() method to insert the elements into storage.

Posted in Code, Tutorials, Web design & development | Leave a comment

More JavaScript Secrets


JavaScript Secrets

Anonymous functions

Why anonymous functions are so very important: they can be used for various purposes such as event handlers, callbacks, methods for objects etc

// using anonymous function as event handler
button.onclick =
    function(){alert("hello portfour");};
// using anonymous functions as a method of an object
var port = {
    dock: function() {
          alert("Portfour is good for docking");
    }
};

port.dock();
// as a callback in an event handler

setTimeout(
    function(){alert("Ship leaves port in 500 milliseconds"); },
    500);

In the second example, even though the anonymous function is assigned a property named dock, the function does not acquire this name. To confirm this test for the function’s name property and you will find that it is still an empty string, not Null or undefined, but a string with length zero.

Recursion

The simplest definition is a self referencing function that converges toward termination. If it is self referencing but does not converge then you have an infinite loop!

// simple recusion, where a function returns a reference to itself
  function isPalindrome(text){
      if (text.length <= 1) return true;
      if(text.charAt(0) != text.charAt(text.length - 1)) return false;
   return isPalindrome(text.substr(1, text.length - 2));
}
// a simple function that counts backwards using recursion
function countDown(nbr){
  console.log("count is " +nbr);
  if (nbr > 1 ) {
   return countDown(nbr - 1); }
return false;
}

var port = {
   countDown: function(nbr){
              console.log("port count is " + nbr);
              if( nbr > 1 ) {
              this.countDown(nbr - 1)};
              return false;
};

}
port.countDown(7); // counts down from 7 to 1

run the code
The first example above shows recursion using a named function, that calls itself by name. This is a simple illustration of the concept, how about anonymous functions? How do you call something that has no name? Remember the example of anonymous functions used as methods? Well, since the method can be invoked using the property name, the anonymous function is also invoked this way. This allows you to call the method from another object property of the same name. The reference to the anonymous function still works even after the initial object has been reset and its properties no longer exist

var ship = {
    signal: function(n) {
            return n >1 ? this.signal(n-1) + "-beep" : "beep";
    }
};

var frigate = { signal: ship.signal };

ship = {};

if(frigate.signal(3) == "beep-beep-beep") alert("The method correctly calls itself");
alert(typeof ship.signal); // returns undefined

run the code

Inline named functions

What do you do when the methods have a different name from the property being referenced? The previous example only applies in a specific case where signal is the name used for both method and property. A more flexible approach would involve giving the anonymous function a name, this is called an inline function.

var port = {
    ship: function signal(n) {
       return n > 1 ? signal (n - 1) + "-beep" : "beep";
   }
};
if(port.ship(3) == "beep-beep-beep"){
   alert("Inline function recursion worked");
};

var frigate = { ship: port.ship };

port = {};
if(frigate.ship(3) == "beep-beep-beep"{
   alert("The inline function correctly calls itself");
};

Next post will look into functions as object and self-memoizing functions

Posted in Code, Tutorials, Web design & development | Leave a comment

Javascript Secrets: Scoping Functions and Function Scope


JavaScript Secrets

Intro

Over the last few years, JavaScript has become an increasingly important Web Development language. Several Libraries and frameworks have been created by leveraging the functional nature of the language to simulate Object Oriented properties intrinsic to more robust languages like Java and C++. (For those who still think Java and JavaScript are similar here’s a great analogy: JavaScript is to Java like hamburger is to ham)

More about Functions

In order to be very good in JavaScript, it is very important to have a good grasp of Functions. Unlike most other languages JavaScript Functions are “first class objects”. This means that Functions can:

  • have methods and properties
  • be assigned to variables, array members or properties of other objects
  • be passed as arguments in other functions
  • be returned as values from other functions

Code samples of Functions

// assigning value to a function
var value1 = function() { return true};

//function as argument in a method call
document.addEventListener("click", function(){
    //do something cool here
    }, false);

// returning a function
function myFun () {
   var nbr = 0;
   return function (){
      var nbr2 = nbr + 2;
   };
}
  • Functions are first class objects they can be created vis literals, assigned to variables, passed as parameters, returned as function results, possess properties and methods
  • Passing a function as a parameter usually involves anonymous functions. Yes, functions can either have a declared name or no name at all
  • Each function invocation is assigned two implicit parameters: arguments and this. The arguments parameter is an “array like” collection of the function’s arguments, it is similar to an array since it has a length property and can be iterated with a for loop, however the data type is object not array.
  • Functions can be invoked via the apply() and call() methods, this allows us to change the context i.e value of this parameter
  • variables in a function are in scope from declaration point to end of the function (n.b declaring a variable with var makes it declared but not defined within that function before it’s defined, so it will be type undefined)
  • Inner named functions are in scope throughout the function enclosing them, even before being defined( this is called hoisting)
//function's name is myName
function myName (arg1, arg2){
// do something here
return value1

}
// function is anonymous has no name
function (arg1, arg2){
// do something here
return value2
}
<script>
	function assert (value, desc) {
		var li = document.createElement("li");
		li.className = value ? "pass" : "fail";
		li.appendChild(document.createTextNode(desc));
		document.getElementById("results").appendChild(li);
		}

		window.onload = function(){
			assert(true, "The test suite is running yay!");
			assert(false, "Fail");
		};
</script>
// css for the assert test function
<style>
	#results li.pass { color: green;}
	#results li.fail { color: red;}
</style>
// HTML for the assert test function
<body>
        <ul id="results"></ul>
</body>
Posted in Code, Tutorials, Web design & development | Leave a comment

jQuery TO



The upcoming two-day conference (1-2 March 2013) in Toronto ( @ The Delta Chelsea 33 Gerrard St. W. Toronto, M5G 1Z4), promises to be very educational and essential for all Front-End Web Developers in the GTA.Featuring over 30 speakers including:

  • Paul Irish – Google Chrome Web development leader and modernizr co-creator read more
  • Addy Osmani – Google Chrome Developer Programs Engineer, read more
  • Scott Gonzalez – jQuery UI Project lead, read more
  • Scott Methvin – President jQuery Foundation.

Even though “Mr jQuery” himself – John Resig, will not be there it’s still worth the $250 registration fee.
Get more details and register @ jQueryTO

Posted in Media, Web design & development | 1 Comment

HTML5 vs Flash – a web based TKO?


Agent 008 Ball

HTML5 vs Flash – a turff war on the WWW

Recently, I stumbled upon some amazing HTML5 demos and apps. One example, Agent 008 Ball (image above), could easily pass for a Flash based game. After playing this game and reviewing a few other apps, I was motivated to write another blog post about the pros and cons of Flash vis-a-vis HTML5. Over a year ago, I published a blog post supporting Flash against HTML5. Back then it seemed to make sense because there were so many features in Flash that HTML5 could not match (a powerful OOP language, a mature IDE, multimedia integration etc.). Now with the countless developments in HTML5, it seems Flash is facing very serious competition. Thanks partly to people like Google’s Paul Irish and others at HTML5rocks.com.

Making Javascript more object oriented

Google’s Closure library allows you to extend Javascript Event Handling feature. You can define custom events and listeners.Thus improving Javascript’s built-in Observer (publisher/subscriber) pattern (e.g. onMouseover, onClick, onLoad etc.). Imagine what can be done with that… in Game Development you can trigger other functions when the player gets a certain score. Or if you have collision detection, fire some other actions whenever certain objects collide. You can also create an event for when the game ends.From an OOP perspective, it is much easier to decouple the Objects in your application. In other words you can separate the “cause from the effect”. An event created in one class can have a listener in a different class. Changing the event trigger (e.g. from a mouseover to an onclick event) requires a single event definition code edit which is then dispatched to all subscribers or listeners. Javascript’s native events would require code changes everywhere the event has been used. Therefore, with the Close library your code is much more flexible, adaptable and reusable.The example below is a call to goog.events.listen() and shows how a click event on contentElement triggers the openEditor() function.

eightball.PocketDropEvent = function(ballNumber, opt_target) {
  goog.events.Event.call(this, eightball.PocketDropEvent.TYPE, opt_target);

  /**
@type {number}
*/
  this.ballNumber = ballNumber;

};
 this._dispatchGameEvent(eightball.Game.EventType.END);
 goog.events.listen(this.contentElement, goog.events.EventType.CLICK,this.openEditor, false, this);

The Closure Library also implements true OOP inheritance mechanism. Allowing you to make your applications much more modular and reusable. Normally Javascript would require you to define a “Prototype chain” for each pair of Objects in a “Parent – Child” relationship. Using the Closure library makes this process less painless, more reliable and consistent across different browsers.

goog.ui.MenuButton = function(content, opt_menu, opt_renderer, opt_domHelper) {
  goog.ui.Button.call(this, content, opt_renderer ||
      goog.ui.MenuButtonRenderer.getInstance(), opt_domHelper);

  // Menu buttons support the OPENED state.
  this.setSupportedState(goog.ui.Component.State.OPENED, true);

  if (opt_menu) {
    this.setMenu(opt_menu);
  }
  this.timer_ = new goog.Timer(500);  // 0.5 sec
};
goog.inherits(goog.ui.MenuButton, goog.ui.Button);

Extended and Improved CSS3

With SASS, you can now define variables in your CSS code. Commonly used values like font colors or margins can be replaced with variables. Instead of changing multiple instances of these values, you simple change the variable once, thus reducing code errors and allowing you to create more consistent page layouts.

/* style.scss */

#navbar {
  width: 80%;
  height: 23px;

  ul { list-style-type: none; }
  li {
    float: left;
    a { font-weight: bold; }
  }
}

/* style.scss */

$main-color: #ce4dd6;
$style: solid;

#navbar {
  border-bottom: {
    color: $main-color;
    style: $style;
  }
}

a {
  color: $main-color;
  &:hover { border-bottom: $style 1px; }
}

HTML5 Resources

A list of useful HTML5, Javascript and CSS3 links
Flash to HTML5 using CreateJS

Google Closure library – time tested library, brings true OOP to Javascript

jQuery Boilerplate -Jump-start jQuery plugins development

SASS CSS3 extension -adds nested rules, variables, mixins, selector inheritance to CSS3

LESS – CSS extension -extends CSS with dynamic behavior such as variables, mixins, operations and functions (similar to SASS)

Compass – an open-source CSS Authoring Framework (uses SASS).

Jangaroo project – AS3 to Javascript compiler

Aptana Studio 3 – develop and test your entire web application using a single environment.

CodeKit – Mac toolkit for HTML5 developers

Agent 008 Ball – A cool pool game using HTML5 and Google Closure library

List of cool HTML5 games

Javascript and HTML5 fireworks animation

WebGL examples

Posted in Design, Web design & development | 1 Comment