JavaScript Notes – 4 (Best Practices)

Posted: February 10th, 2012 | Author: | Filed under: technical | Tags: | Comments Off

In this blog article I want to discuss on few of the JavaScript best practices that I have gleaned from various people, talks, videos, books. For the sources, see here.

VAR, WHERE?

To start with declaration of variables. The best way to do it is

var oneVariable,
    anotherVariable,
    oneArray = [],
    oneObject = {};
// do your thing

Points to notes -
- Good formatting
- Initialization of arrays and object literals without using new is much cheaper (as scope resolution is not required).
- Do not forget the commas after each of the variables

Staying on the topic of variables, there is a useful-to-know concept of hoisting . The following code segment will elucidate the idea-

var foo = 1;
function bar() {
	if (!foo) {
		var foo = 10;
	}
	alert(foo);
}
bar();

Can you guess the output? Click show source below for answer and explanation.

/* the code above re-written to explain 
 * how the interpreter sees it
 */
var foo = 1;
function bar(){
    var foo; // the declaration of foo is hoisted to the top of the scope and undefined
    if(!foo){ // foo is undefined now, this foo not the global variable 
        foo = 10; // set the value of the local variable foo
    }
    alert(foo); // alert foo, the local foo 
}
bar(); // alerts 10

So that is the idea of hoisting explained simplistically. The lesson is to have all your var statements together at the top of the function to avoid such issues. There is something similar that happens with functions too, you can read more about it in Ben Cherry’s article. Long story short, you would want to define your functions before using them.

Do remember that JavaScript has function-level scope, not block level scope . You can create block level scope using anonymous, immediately-executing functions. I will do a more detailed blog post on JavaScript scoping and chaining later.

ARRAYS, LOOPS, YEAH TOGETHER

var a = [];
console.log(typeof a); // "object" Arrays are objects, not arrays. 
console.lo(a.length); // 0

a[10] = "nadu";
console.log(a.length); //11 

a["another_element"] = "another nadu";
console.log(a.another_element); // another_nadu
console.log(a.length); // 11 (still)

This means that arrays are slow, because they are effectively represented as objects. So, the easiest way to improve performance is to NOT do this

var i,
    elements = document.getElementsByTagName("div"); // a huge array
for(i=0; i<elements.length; i++){
    //add a class to the div
    // do something else
}

What is wrong? Well, in each iteration, the length of the elements array is calculated instead just cache the length in a variable and compare it with the loop variable. No big shakes at all right? Well do remember to do this for big arrays!

var i,
    elements = document.getElementsByTagName("div"), // a huge array
    l = elements.length;
for(i=0; i<l; i++){ 
    //add a class to the div
    // do something else
}

DOOM DOM

Few rules for manipulation of the DOM gleaned from this talk.

USE FRAGMENTS TO APPEND NEW ELEMENTS

Assume, you have a container div element and you want to create the child div elements after getting some JSON data from an external server. For appending the child elements,

var i,
    cDiv = document.getElementsById("container-div"), 
    l = jsonResponse.length ;
for(i=0; i<l; i++){ 
    var newChild = document.createElement("div");
    newChild.innerHTML = jsonResponse[i];
    cDiv.appendChild(newChild);    
}

The problem here is that if there are 100 children divs that are going to be created, then the live DOM will be modified 100 times for appending each child div and the performance takes a hit. Instead, the better method is to create a document fragment, append your nodes to the fragment and then attach the fragment to the live DOM.

var i,
    cDiv = document.getElementsById("container-div"), 
    frag = document.createDocumentFragment(),
    l = jsonResponse.length ;
for(i=0; i<l; i++){ 
    var newChild = document.createElement("div"); 
    newChild.innerHTML = jsonResponse[i]; 
    frag.appendChild(newChild);    
}
cDiv.appendChild(frag); // hurray only once do you touch the live DOM

Useful JavaScript Fact – Did you know that you do not need to convert your object keys to strings unless they are a keyword in JavaScript –

var obj = {
    "name" : "Nadu",
    "is_human": true
    "class": "Less Awesome"
}
// instead write 
var obj = {
    name : "Nadu"
    is_human: true
    "class" : "More Awesome"
}


Next planned article on jQuery and its goodness.

Credits

Ben Cherry’s (a Twitter Engineer) blog – http://www.adequatelygood.com
Paul Irish’s talk here


JavaScript Notes – 3 (Pub/Sub)

Posted: January 20th, 2012 | Author: | Filed under: technical | Tags: , | Comments Off

In this blog post I cover the implementation of Publisher-Subscriber (a.k.a Observer) Design Pattern in JavaScript. As the name suggests, the Pub-Sub model is a way by which an entity can publish events/messages and multiple entities can subscribe to those events/messages and subsequently take action. Browser event are examples of this pattern where the browser publishes events like keypress, mouseclick etc. and event handlers in JavaScript can have act when those events occur.
The example explained below can be seen live here. They are from the book JavaScript Patterns
The publisher, say paper which publishes a daily and a monthly magazine and a reader say, joe will be notified when that happens. A publisher object would need the following members for implementing the functionality

subscribers = [] //- an array (list) of all subscribers
subscribe = function(){} //- a method to add to the list of subscribers
unsubscribe = function(){}  //- a method to remove from the list
publish = function(){} //a method to notify all subscribers by calling the methods they provided when they signed up
//All the 3 methods above will need a type parameter as there can be many different type of events

Since these methods are generic to any publisher, it is better to implement this as a separate object. Then we can copy these properties over to any object and convert any object to a publisher (we will see this in a bit).
The code snippet below defines each of the methods and the subscribers array mentioned above.

var publisher = {
    subscribers: {
        any: [] // event type: subscribers
    }, // an object with different event types

    subscribe: function (fn, type) {
        type = type || 'any';
        if (typeof this.subscribers[type] === undefined) {
            this.subscribers[type] = [];
        }
        this.subscribers[type].push(fn);
    },
    unsubscribe: function (fn, type) {
        this.visitSubscribers('unsubscribe', fn, type);
    },
    publish: function (publication, type) {
        this.visitSubscribers('publish', publication, type);
    },
    visitSubscribers: function (action, arg, type) {
        var pubtype = type || 'any',
            subscribers = this.subscribers[pubtype],
            i,
            max = subscribers.length;
            
        for (i = 0; i < max; i += 1) {
            if (action === 'publish') {
                subscribers[i](arg);
            } else {
                if (subscribers[i] === arg) {
                    subscribers.splice(i, 1);
                }
            }
        }
    }
};

Now we have a generic publisher using which we can convert any object to a publisher. The way we do it is that we copy the function properties of the generic publisher to the object. Sweet?

function makePublisher(o) {
    var i;
    for (i in publisher) {
        if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") {
            o[i] = publisher[i];
        }
    }
    o.subscribers = {any: []};
}

Now say we have the paper object which publishes daily and monthly (2 events). So you can have the object as

var paper = {
    daily : function(){
           this.publish("Daily news publication - Breaking News Today");
    }
    monthly : function(){
           this.publish("30 Days of News!", "Monthly Type");
    }
}
// use the makePublisher method to convert this to a publisher object
makePublisher(paper);

Let’s define our subscriber object, joe

var joe = {
    drinkCoffee = function(paper){
               console.log("Reading paper" +paper);
    }
    readMonthlyDigest = function(monthly){
               console.log("Reading monthly digest"+ monthly);                  
    }
}

// Joe subscribers to the paper
paper.subscribe(joe.drinkCoffee);
paper.subscribe(joe.readMonthlyDigest, "Monthly Type");

So effectively the joe object has bound those 2 methods to those 2 events of the paper object. So whenever the paper publishes (monthly or daily), joe’s methods are called since it had subscribed to them.

// Now paper publishes
paper.daily(); // logs Reading paper Daily news publication - Breaking News Today
paper.daily();
paper.daily();
paper.monthly(); // logs Reading monthly digest 30 Days of News!

So, the joe object does not hardcode the paper object or vice-versa. The objects are loosely coupled and one can be changed without impacting the other (adding new subscribers or new publications- weekly)

The beauty of this loosely coupled pattern emerges now when we can turn joe into a publisher and the paper object into a subscriber.

makePublisher(joe);
joe.tweet = function(msg){
    this.publish(msg);
}

paper.readTweets = function(tweet){
    console.log("Someone tweeted on our blog - " + tweet);
}

joe.subscribe(paper.readTweets);
// so joe can say 
joe.tweet("The news was really boring today");

The above was an example of the Pub/Sub model in JavaScript, useful for loosely coupled objects and when you have time to architect your JavaScript solutions before jumping into code directly.


Thoughts translated in pictures

Posted: November 27th, 2011 | Author: | Filed under: technical | Tags: , | Comments Off

Lone Bright Spot - However much life sucks, there is always, yes always, a bright spot in your life that will lead us to the non-sucky part of life. Love and nurture that bright spot, that might be the reason for one’s existence in this world.





Fields of Moods - Like magnetic fields, our moods have fields, and they affect the people coming in contact with that field. A bright and good mood has a bigger field of impact, whereas dark and gloomy mood has a smaller but more intense field of impact. In our worst moods, we hurt the ones closest to us. In the best of our moods we will be kind and spreading our radiant energy to total strangers.




Perspectives - Every living thing in this world has a point of view, a perspective. These brush strokes represent these diverse perspectives in the world about any given thing. Remember, at the end of the day, you too have a perspective on life, and how you should lead it. Follow that. Believe.


Open-Captions

Posted: October 23rd, 2011 | Author: | Filed under: technical | Tags: , | 1 Comment »

What is Open-Captions?

According to research, over 90% of deaf children have hearing parents who “frequently do not have fully effective means of communicating with them”. The American Sign Language (ASL) is a difficult language to learn, especially as a second language.

Open-Captions makes it easy for parents and children to learn and practice American Sign Language together while watching their favorite videos on YouTube. People can find closed captioned videos on any topic with the Open-Captions search engine. The viewer is able to select individual words in the video’s caption stream and see the American Sign Language representation of the word.

Open Captions Example Screenshot

Closed captions on various television shows have been around for quite some time. They are useful for hearing impaired people and also to people whose first language is not English.
Captions have always been a steady stream of white text on black background, located either at the top or bottom of the screen. Video sites like YouTube and Hulu , have adopted the same style from television.
Open-Captions, changes the way users watch videos by making the captions more interactive.

  • The viewer can pause the video, select a word and watch an ASL representation.
  • The viewer can review earlier captions with the “Previous Caption” button.

The American Sign Language representations are shown from the SmartSign dictionary maintained by Georgia Institute of Technology’s Center for Accessible Technology in Sign (CATS).

How did Open-Captions come about?

My interest in building Assistive Technologies has been one of the main motivating forces behind getting a graduate degree in Computer Science.

I built a web based widget platform for Interactive TV as a graduate student researcher at GeorgiaTech. In the process I worked on developing functionality that would allow widget developers to access the closed captions associated with the currently playing content.
Harley Hamilton, a researcher at CATS, was interested in leveraging this ability of accessing closed captions and we ended up building a rough prototype. Subsequently, I learnt more about hearing impaired children from Harley and wrote a small tool using which one can select any word on a webpage and see the American Sign Language representation of the word. This would be very useful for parents who want to learn ASL.
In September this year, I signed up for the HackdayTV weekend hackathon and ended up building the first version of Open-Captions, which is the mashup of the earlier ideas I had worked on related to ASL.

What happens behind the scenes in Open-Captions?

Disclaimer: Technical content ahead ;)
The entire source code for the project can be found on GitHub
YouTube has extensive documentation on how to use their APIs for search, embedding and controlling videos on your site. The search and results page are based on the PHP library of the YouTube search API. The page on which the video plays is the one that gets interesting. There are 2 parts to it -

  • Getting the closed captions of the video and synchronizing it to show correctly
  • Handling the mouse clicks on the individual words to show the ASL representation

I used Firebug to see what requests YouTube sends whenever you click on the “Interactive Transcript” icon under the video. I removed parameters that were not mandatory (i.e. I would still get the same result if I removed them) and made a PHP curl request for the trimmed URL to get the captions formatted as XML. For this YouTube video the URL for the captions would be


http://www.youtube.com/api/timedtext?lang=en&format=1&v=<VIDEO_ID>&type=track&kind=&hl=en

and the result will be of the form

<transcript>
<text start="0.734" dur="4.299">[Sesame Street theme music]</text>
<text start="5.033" dur="1">Elmo: You okay, Chris?</text>
<text start="6.033" dur="1">Chris: I&#39;m good, I&#39;m good.</text>
<text start="7.033" dur="1">Elmo: You ready?</text>
<text start="8.033" dur="1.067">Chris: Yeah, I&#39;m ready. Oh, hey!</text>
<text start="9.1" dur="1.467">Red light&#39;s on. Hey, hi, everybody.</text>
<text start="10.567" dur="1.034">I&#39;m Chris.</text>
<text start="11.601" dur="1">Elmo: Oh, and Elmo&#39;s Elmo.</text>
<text start="12.601" dur="1.367">Chris: Mm-hmm, he sure is.</text>
<text start="13.968" dur="3.199">
I work at Hooper&#39;s Store right here on Sesame Street.
..
..
</transcript>

As far as I understood, not all YouTube videos with captions could be accessed with the above API call because their caption files had names. Then, I came across this user script which is useful if you want to download the captions file. The author had a snippet of code for retrieving the name of the captions file –


http://video.google.com/timedtext?hl=en&v=<VIDEO_ID>&type=list

this returned an XML with the name of the captions file. I used that to extend my API call to


http://www.youtube.com/api/timedtext?lang=en&format=1&v&<VIDEO_ID>&type=track&kind=&hl=en&name=<CAPTION_FILE_NAME></strong>

Then using JavaScript setTimeout function and the values of the start and duration of the captions, I do the synchronization of the captions and the video.

function showAppropriateCaptions(){
   var i,
     len = global_full_captions.length,
     currTime;
   //my_ytPlayer is the handle of the YouTube player
   if(my_ytPlayer.getPlayerState() == -1){
      return;
   }
   if(my_ytPlayer.getPlayerState() == 1){
      // State = 1 => playing video - so get the time and show appropriate captions
      // this will get triggered automatically when the video starts for the very first time
      currTime = my_ytPlayer.getCurrentTime();

      // to-do: a better way to handle hide show instead of doing at every iteration
      $('.myCaptionSpan').show();// the container having the captions
      $('#previous').show(); // the previous button 
      
      for(i=0;i<len;i++){
        if(currTime < global_full_captions[0].startTime){ 
          // if the captions has not started, call just before the first caption is scheduled
          setTimeout(showAppropriateCaptions, (global_full_captions[0].startTime - currTime )*1000);
          return;
        }
        if(currTime > global_full_captions[len-1].startTime + global_full_captions[len-1].duration){
          // it has ended, no more captions to show
          $('.myCaptionSpan').hide();
          $("#previous").removeClass('enabled');
          $("#previous").attr("disabled",true);
        }
        if((global_full_captions[len-1].startTime <= currTime && ((global_full_captions[len-1].startTime + global_full_captions[i].duration) > currTime))){
          // ugly workaround for showing the last caption
          if(!$('#previous').hasClass('enabled')){
            $("#previous").addClass('enabled');
            $("#previous").attr("disabled",false);
          }
          createBeautifulCaptions(global_full_captions[len-1].captions);
          setTimeout(showAppropriateCaptions,global_full_captions[len-1].duration*1000);
          return;
        }

        if((global_full_captions[i].startTime <= currTime && (global_full_captions[i+1].startTime > currTime))){
          // found the appropriate caption
          if(!$('#previous').hasClass('enabled')){
            $("#previous").addClass('enabled');
            $("#previous").attr("disabled",false);
          }
          createBeautifulCaptions(global_full_captions[i].captions);
          // now call the same function before the start of the next caption
          setTimeout(showAppropriateCaptions,
                     Math.abs(global_full_captions[i+1].startTime - global_full_captions[i].startTime)*1000);
          return;
        }
   }

}

Now, for every word in that particular line of the caption, I broke it up into span elements and attached click handlers to each. The span elements look like this

<p class="mycaption" >
<span id="beautifulCaptions0">to</span>
<span id="beautifulCaptions1">spend</span>
<span id="beautifulCaptions2">some</span>
<span id="beautifulCaptions3">good</span>
<span id="beautifulCaptions4">time</span>
<span id="beautifulCaptions5">with</span>
<span id="beautifulCaptions6">my</span>
<span id="beautifulCaptions7">good</span>
<span id="beautifulCaptions8">buddy</span>
<span id="beautifulCaptions9">Elmo</span>
<span id="beautifulCaptions10">over</span>
<span id="beautifulCaptions11">here.</span>
</p>

When a word is clicked on the captions, the showASL method gets called and the word string is passed as a parameter. After stripping the words of extraneous characters like !, &, ], [, ; etc and converting the word to lowercase, the method inserts an iframe on the right hand top corner whose URL points to

http://cats.gatech.edu/cats/MySignLink/dictionary/html/pages/<THE SELECTED WORD>.htm

The pages showing the ASL have flash videos embedded, so I have styled the iframe so that the flash video is at the center of the box. Some of the pages have just images and some may have both. Hence, I added the “Full Page View” button under the ASL box, so that viewers could see the entire page if they wanted to.

The SmartSign website covers around 25000 words and hence there will be words in the captions for which the ASL representation do not exist. For such cases, I get an image from Bing to substitute for the ASL.
The source code is undergoing constant refactoring, and would love to get more ideas on how to design a better solution.

What lies ahead for Open-Captions?

Currently, I am gathering feedback from hearing impaired users about Open-Captions and also getting thoughts on what additional features they would like. Harley, the researcher at CATS, is excited about this project too and reaching out to more people for feedback.
Another idea is to build Open-Captions as the “Khan Academy” of ASL, by having videos that enable different levels of learning of ASL.


JavaScript Notes – 2

Posted: October 21st, 2011 | Author: | Filed under: technical | Tags: | 1 Comment »

In this blog post, I am introducing Custom Constructor functions, a method for “Classical Inheritance” in JavaScript and Prototypal inheritance in JavaScript. The knowledge in this post is condensed from Stoyan Stefanov’s book JavaScript Patterns.
While trying to understand Prototypal inheritance in JavaScript, I realized that I needed to grasp the above concepts strongly. So hence this post touches upon a breadth of topics.

Custom Constructor Functions

3 ways of creating objects in JS –

var myObject1 = {}; // literal notation
var myObject2 = new Object();
var myObject3 = new MyConstructor(); // custom constructor

The third way is what we are interested in currently. So, it looks the same as we would do in Java to create a new object of a class MyConstructor. Below is one way that the function MyConstructor can be defined. (Do remember that MyConstructor is a function at the end of the day. The capitalized first letter is a coding practice to differentiate custom constructors from functions)

var MyConstructor = function(name){ 
    this.name = name;
    this.hello = function () {return "Hello "+this.name;};
}
var obj = new MyConstructor("nadu");

When we call MyConstructor with new, 3 things happen inside the function

  • An empty object is created and referenced by this variable, inheriting the prototype of the function.
  • Properties and methods are added to the object referenced by this.
  • The newly created object referenced by this is returned at the end implicitly (if no other object was returned explicitly).

In the above example, the hello was added to this. So each time new MyConstructor gets called, a new function hello is created in memory. Since the method hello does not change from one instance to another, we can add that to the prototype of MyConstructor.

MyConstructor.prototype.hello = function(){
    return "Hello "+ this.name;
}

A prototype is an object and every function you create automatically gets a prototype property that points to a new blank object. You can add functions to the prototype and they will be accessible to all the objects created using new MyConstructor()

There are 2 different ways inheritance (code-reuse) can be done in JavaScript. One is to create classes to emulate the typical (class-ical) inheritance and the other is using the prototypal nature of the language.

Classical Inheritance

This can be implemented in JavaScript based on custom constructors. Below is just one pattern (simplest) of implementing classical inheritance. Refer to the book for different implementations.

// parent constructor
function Parent(name){
   this.name = name || "Adam";
}
// add functionality to the prototype
Parent.prototype.say= function(){
    return "Hello "+ this.name;
}

The hidden link __proto__ points to the prototype property of the constructor function that created that object.

//child constructor
function Child(){}

//inherit - C will have access to P's properties
inherit(Child,Parent);

var kid = new Child();
console.log(kid.name);//"Adam"
console.log(kid.say()); 

// here is how inherit is defined
function inherit(C,P){
    C.prototype = new P();
}

Working Example on JS Fiddle

Prototypal Inheritance

In Prototypal inheritance, objects inherit from objects. You have an object that you would like to reuse and you want to create a second object that gets functionality from the first one.

var parent = {
    name:"Parent"
};

// the new object which inherits parent
var child = object(parent); 

console.log(child.name); // Parent
console.log(child.prototype);
console.log(child.__proto__);


// here is how object is defined
function object(o){
    function F(){};
    F.prototype = o;
    return new F();
}

An important thing to understand is that the child.__proto__ points to the parent object. The __proto__ link points to the prototype property of its parent constructor which was the temporary function F. The __proto__ link is what makes the interpreter check for the property name in its parent.

The console output showing the values of child.name, child.prototype, child.__proto__


I am guilty of screen scraping

Posted: October 2nd, 2011 | Author: | Filed under: technical | Tags: , | 1 Comment »

I love data visualization. I am inspired by the fact that India has a wealth of data that can lead to wonderful visualizations that can help Government officials, politicians, journalists, social workers do their daily jobs better. Even the average citizen should be able to see the visualization and understand what’s going on and maybe get inspired to be a more responsible citizen.
I am on the constant lookout for Government data that is openly accessible and see if I can do something interesting with it. That led me to build this visual guide of elected representatives of India and this blog entry comparing corruption at the higher levels and by average citizens
There are a lot of websites (usually run by NGOs) that have data about Indian politicians and their details (education, criminal records, attendance in the parliament, participation in the parliament etc). This website has data on criminal records that made me interested. I emailed them asking (hoping) if they have any APIs that can be used to access the data, but I guess that is not high on their priority list. However, what they had was data arranged in HTML tables and lots of pages numbered serially. So I got into screen scraping mode and scraped out information of around 7800 candidates who stood in the elections in the Indian General Elections in 2009. Now, I have their educational qualifications, criminal records, total assets and liabilities (some have really obscene numbers) in my database.
The goal is now 2 fold.

  1. Create a simple visualization on the map of India to show educational qualifications, assets information and criminal cases of these candidates. Give the ability to filter by party, state. So viewers can see which areas had more educated candidates, which had more criminal candidates and where did the richest candidates come from.
  2. While creating the above goal, ensure that the API to access data is well written so that it can be exposed to other developers interested in building more cool visualizations.

This should be fun.


Open Captions

Posted: September 11th, 2011 | Author: | Filed under: technical | Tags: , , , , | 12 Comments »

[Updated with the latest status of Open Captions project]

I started building Open Captions for the Hackday TV hackathon at General Assembly.

Open Captions gives the viewers, the ability to search and view closed captioned YouTube videos. While watching the video, the viewer can select individual words of the closed captions and then see an American Sign Language Representation of the word on the screen. The viewer can also jump back to the previous caption showed on the screen. Whenever, a word is selected, the video automatically pauses when the ASL is showed on the page. The working prototype can be seen on Open Captions

Currently the project is a work in progress, and is susceptible to fail at a few places. Please feel free to email feedback, ideas, suggestions about Open Captions.

The ASL representation is just one of the use cases of Open Captions. This can be linked with Google Translate to find out words in other languages (very useful for people for whom English is not the first language). This can also be linked with say Wikipedia and children can learn about a word or a place spoken about on TV.

This idea of selecting words from closed captions also works for videos from Universal Subtitles, an initiative which helps create closed captions for videos on the Internet. Open Captions example with Universal Subtitles

Reference
The ASL representations are being scraped from www.cats.gatech.edu, which has around 25000 words shown in ASL in 25000 web pages.


JavaScript Closure Example

Posted: September 2nd, 2011 | Author: | Filed under: Uncategorized | Tags: , | Comments Off

It has taken me time to fully understand the concept of closures in JavaScript. Here is an example of code that I rewrote so that we can use closures and get the thing to work the way we actually want it to.

The situation:
We have a set of buttons and we have to attach on-click handlers to them. These handlers should be called with parameters that are button dependent i.e., the innerHTML of the text box next to that particular button or say we need some attribute of the button (data-value, or some custom attribute).

We want to attach a function inviteUserToGroup with the specific parameters as event handlers to all the buttons.
So we initially wrote :

//add event handlers to invite buttons
var inviteBtns = $$('.inviteBtn'); //Prototype to get an array of elements with this class name
var len = inviteBtns.length;
var i;
var groupIdForUser;
var detailsForUserInGroupName;

for(i=0;i<len;i++){
    groupId = $('groupIdForUser'+i).innerHTML;
    details = $('detailsForUserInGroupName'+i).innerHTML;
    //Protoype syntax to attach event handlers 
    //Event.observe(element,event,handler)
    Event.observe(inviteBtns[i],'click',function(){
        inviteUserToGroup(groupId,i,details);});
}

function inviteUserToGroup(a,b,c,d){ doSomething();}

So, we attach inviteUserToGroup method with the parameters. Since we enclosed the handler as a function, one can assume that due to the scope of the function, it should work fine and the event handler will be called with the correct parameters. That doesn’t work that way. All the event handlers get called with the value of i = len. You thought closures would work here, but it does not.
So what do you do? Create a real closure. The following code does that

/* DOES NOT WORK
Event.observe(inviteBtns[i],'click',function(){
    inviteUserToGroup(groupId,i,details);});
*/

Event.observe(inviteBtns[i],'click', 
    (function(gId,i,dtls){
        return function(){
                   inviteUserToGroup(gId,i,dtls);
               }
        })(groupId,i,details)));

So what is happening?
1) Create an immediate anonymous function which takes in the parameters that you want in your handler.
2) In the anonymous function return the actual function with parameters that you want to call. In this case we return inviteUserToGroup() with the parameters.
The important point to understand is that, the immediate function will execute and hence have the current values of groupId, details and i, which are passed to it. Due to the closure, the inner function (which is returned) has access to these values even after anonymous function has completed execution. So, inviteUserToGroup is attached to each button with the correct parameters.

For completion, another way of doing this is

Event.observe(inviteBtns[i],'click',
    'inviteUserToGroup('+groupId+','+i+',\''+details)');});

Not recommended by many people as this uses the eval function to evaluate the JavaScript inside the quotes.

Is there a better (maybe more legible) way of doing this? Let me know!


JavaScript Notes – 1

Posted: August 19th, 2011 | Author: | Filed under: technical | Tags: , | Comments Off

My notes on JavaScript Patterns. This is just a part of the patterns covered by Addy Osmani and those covered by Stoyan Stefanov

**Disclaimer**: The code examples below are modified examples from JavaScript Patterns

Namespaces
Using global variables and functions in JavaScript can lead to smashing of variables as the code base grows. So a simple way of handling namespaces is

var NxJ = {};
NxJ.property1 = "Name is Nadu";
NxJ.method1 = function(){console.log("name is bond, james bond");}

// if you want to add modules
NxJ.modules.module1 = {};
NxJ.modules.module1.data = {"a":1,"b":2};

var moduleToBeUsed = NxJ.namespace("NxJ.module1.module2.module_n");

The variable names keep getting larger and larger. A way to handle this is to create a function called namespace, that can parse the module name and return only that module with all the methods. Useful when you are using big libraries like YUI (they have different modules for DOM, Events etc)

Private properties, Module and Revealing Module
By default everything is public

var myObj = {
	myName : “Nadu”;
	getName = function(){
		return myName;
	}
};
console.log(myObj.myName); // accessible

So a way of fixing this is

myObj = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	return: // yes return an object
	{
            getName = function(){
               return myName;
            }
	};
}());

console.log(myObj.myName); // inaccessible now
console.log(myObj.getName()); // this is the right way to get it

Points to note -

  • Immediate function call – so what value does myObj get?
  • var before myName makes it private because of closure
  • getName is a privileged function

Lets add namespaces now,

var NxJ = {};
NxJ.coolModule  = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	var yourName = “Someone else”;

	return:
	{
              getName = function(){
		   return myName;
	      },
	      setName = function(n){
			myName = n;
              }
	};
}());

So that’s the Module pattern!
Since we have reached alive till here, we will jump to the Revealing module pattern, which is nothing but a simple extension of the Module pattern.
In the Revealing module pattern, you define all the properties as private in the object and then return only those that you want to be made public

var NxJ = {};
NxJ.coolModule  = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	var yourName = “Someone else”;
        var getName = function(){return(myName);};
	var setName = function(n){ myName = n;}

	return:
	{
		getName: getName,
		getTheAwesomeName: getName // sort of an alias!
	};
}());
console.log(NxJ.coolModule.getName());
console.log(NxJ.coolModule.getAwesomeName()); // this works too

There are 2 advantages of this pattern, one is that it’s a little more cleaner than the Module pattern and two you can have these aliases. One can create a JavaScript API and then just return all that is public.

Be careful!

var NxJ = {};
NxJ.coolModule  = ( function(){
    // a var before myName - makes it private 
    var student = {"name":"Nadu", "age":"18-till-i-die"};
    var getStudent = function(){ return student; }    
    
    return    {
        getStudent: getStudent
    };
}());
var stud = NxJ.coolModule.getStudent();
console.log(NxJ.coolModule.student); // not possible
console.log(stud.name); // says Nadu
stud.name = "Narayanan Ramakrishnan"; // trying to modify it
var stud2 = NxJ.coolModule.getStudent();
console.log(stud2.name); // prints Narayanan Ramakrishnan - Hey WTF ?

This is because for arrays and objects, JavaScript returns the reference, so its accessible to anyone who has the reference. So one way of handling this is to return a new object that has properties that the caller is interested in. Called the Principle of Least Authority which states that you should never give more than intended. One way of doing this in the example above is, instead of giving the caller everything, you can break it down into functions getName(), getAge(). There is another approach using a general purpose cloning function, but that will be covered later.

More notes to follow in another post.
Further reading
A beautiful explanation of Module Pattern by Twitter engineer Ben Cherry
Signing off treat – www.jsfiddle.net


ASL Dictionary Greasemonkey script v0.1

Posted: April 15th, 2011 | Author: | Filed under: technical | Tags: , | 1 Comment »

Research says that around 90% of hearing impaired children are born to hearing parents. So if parents do not know Sign Language then it is difficult for the child to learn ASL quickly. Wouldn’t it be great if people could learn sign language on the fly when they are reading articles on the web? Maybe they are reading stories to their children from a website and they can have ready assistance to translate words in written language to Sign Language. So, I thought of creating a simple Greasemonkey script that would show the ASL equivalent of a selected word.
Center for Accessible Technology in Sign at GeorgiaTech has a huge database of words and their American Sign Language equivalent. I used their web pages that they had created for around 25000 words. Whenever a word is selected, I load the ASL equivalent in an iframe on the right top corner of the page.

To Install

Here are the steps to try it on Firefox

  1. Open Firefox (version 3.0 – 4.0.*)
  2. Install Greasemonkey if you are using Firefox
  3. Click on this link to download the script
  4. Let Greasemonkey install the user script.
  5. Now open any webpage say – Wikipedia entry on ASL
  6. Now select any word (not phrases/sentences) – for example – Sign, Language, also, common, English or languages

You will see the American Sign Language representation of the word on the top right.
If a word that does not exist in the database is selected then, it shows “Sorry word could not be found”.

Here are the steps to try it on Chrome

  1. Open Chrome
  2. Click on this link to download the script
  3. Let Chrome install the user script.
  4. Now open any webpage say – Wikipedia entry on ASL
  5. Now select any word (not phrases/sentences) – for example – Sign, Language, also, common, English or languages

You will see the American Sign Language representation of the word on the top right.
If a word that does not exist in the database is selected then, it shows an error message.

An example, with the word Languages highlighted

Another example, with the word Sign highlighted

The representation automatically hides after 5 seconds. (So if you click on another word before 5 seconds, the results may be buggy)
Update

To Uninstall
To uninstall on Firefox, click on the Greasemonkey icon and disable the ASL Dictionary.
To uninstall, open chrome://extensions/ and disable the ASL Dictionary.

For future versions
1) If you select a phrase, it shows the sequence of signs
2) Fix “Word not found” error in Chrome
3) Ability to select the word, right click and have the option to play the video or the cartoon


#hackersagainstdiscrimination

Posted: March 27th, 2011 | Author: | Filed under: Uncategorized | Comments Off

I have started painting using watercolors again. It’s a beautiful feeling. I realized that I could create different skin colors using the paint and that can either lead to a cartoon like these or something different. Just loved this idea!

Disclaimer – This is the first time I tried drawing Tux.


PHP-JSON Special Characters

Posted: January 28th, 2011 | Author: | Filed under: Uncategorized | Tags: , , , , | Comments Off

Wanted to share this with the group since it took me 3 hours to figure this out.

I was trying to retrieve JSON data from a third party service using a PHP.
In PHP , if you use curl_exec() functions to retrieve JSON data, it returns it in a string form. You can do json_decode($string, true) to retrieve it in an associative array form.

$url = "www.example.com/data.json";
	$curl = curl_init();
	curl_setopt( $curl, CURLOPT_URL, $url );
	curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
	$result = curl_exec( $curl );
	curl_close( $curl );
        $return = json_decode( $result, true);
        echo $return["description"];

All is fine if your json data doesn’t have special characters like “é”, for example

{
"description":"Eric Benét performs.",
"origAirDate":"2011-01-27", 
"stationId":11269,
"endTime":
"Thu Jan 27 11:00:00 EST 2011","startTime":"Thu Jan 27 10:00:00 EST 2011",
"title":"The Wendy Williams Show",
"isVisible":true,
"rating":"TV-PG"
}

To handle these special characters make sure that you do

 $result = utf8_encode($result); // before json_decode
 $return = json_decode( $result, true);
 echo $return["description"];

Source

Hope this helps


ns2.34 setup on Ubuntu Lucid Lynx 10.04

Posted: September 17th, 2010 | Author: | Filed under: technical, Uncategorized | Comments Off

Setting up ns2 on Ubuntu (Lucid Lynx 10.04),

$ sudo apt-get update
$ sudo apt-get install build-essential autoconf automake libxmu-dev libxt-dev libxt6 libsm-dev libsm6 libice-dev libice6 vim

Download ns-allinone.2.34.tar.gz – http://sourceforge.net/projects/nsnam/files/allinone/ns-allinone-2.34/

$ tar -xvzf ns-allinone.2.34.tar.gz
$ cd ns-allinone.2.34/
$ ./install

You might hit the error
otcl-1.13 make failed! Exiting

Solution
in otcl-1.13/configure file -
replace

Linux*)
SHLIB_CFLAGS="-fpic"
SHLIB_LD="ld -shared"
SHLIB_SUFFIX=".so"
DL_LIBS="-ldl"
SHLD_FLAGS=""
;;

with

Linux*)
SHLIB_CFLAGS="-fpic"
SHLIB_LD="gcc -shared"
SHLIB_SUFFIX=".so"
DL_LIBS="-ldl"
SHLD_FLAGS=""
;;

This should work now.
Note for this to work the CC value in Makefile.in inside otcl folder should be @CC@. It did not work when I changed it to gcc 4.3
Hope this helps