Archive for the ‘black belt’ Category.

How to make sure undefined is not defined

Think about it, you write a plugin or a library (let’s name it jsKata) and your code contains checks to see if certain things are undefined.

Here’s an example :

  1. if (obj.name === undefined) {
  2.   obj.name = "This object has no name";
  3. }

This code works well until you include another script (found on an obscure website) and it breaks your previous code. By debugging the code, you see the value of undefined is no more undefined but false.

Yes, I know that you thought it was impossible to define undefined but it is, you just have to write undefined = false.

Redefine undefined

There’s two way of redefining undefined and they both use self-invoking functions.

Method 1 : Scope your code

  1. (function(undefined) {
  2.   /* your complete code here */
  3. })();

As you see, the self-invoking function has one parameter named undefined. At line 3, the self-invoking functions is called without any parameter. It results that the parameter has the value undefined (or it is defined to undefined if you prefer).

Take a look at this javascript :

It will display false and then display undefined even if undefined was globally defined at first.

This is the HTML that goes with it :

You can also execute it here.

Method 2 : Globally redefine undefined

There’s another method but I don’t like it that much. It redefines undefined but nothing protects it from being badly redefined in another chunk of code.

undefined is a global variable accessible using the global window object. Line 2 defines undefined and line 3 display the value of undefined as false. On line 4, I use a self-invoking function as method 1 does but now, I define the global undefined variable through the global window object.

The HTML of this example :

You can also execute it on jsFiddle.

Other methods

Some commentors pointed me other ways of doing it.

You can use typeof :

  1. typeof undefined == "undefined"

Or you could use void(0), it always returns undefined

  1. undefined === void(0) // this returns true

Self-invoking functions explained line by line

I never knew it was possible to love a syntax but since, I fell in love with the self-invoking function which can be summarized like this : (function(){})(). Yes this is a valid syntax though it doesn’t do much in this form (it creates a function that does nothing and call it).

Some people call it self-invocation or self-executing but I don’t think it has an official name.

Let’s break it down

It will become clearer if I execute some code and write it on more than one line :

  1. (
  2.   function() {
  3.     console.log("this line is called");
  4.   }
  5. )
  6. ();

Line 1 : (
This first parenthesis is used as grouping operator. Read more here and here.

Line 2 : function() {
This create an anonymous function. I could write something like function doSomething() { but in the case of a self-invoking function, this is useless because the function is in its own little scope (line 1) and can’t be called from outside of it.

Line 3 : console.log(“this line is called”);
This is the code that will be invoked.

Line 4 : }
This clauses the function opened at line 2.

Line 5 : )
Clauses the parens opened at line 1.

Line 6 : ();
We call the function created at line 2 and returned within the scope from line 1 to 4.

Let’s write it in a more compact syntax :

  1. (function() {
  2.   console.log("this line is called");
  3. })()

See my post about using self-invoking functions to create namespaces.

Don’t forget to subscribe to my newsletter!

NoFreeze : a library that avoids freezing in javascript

The unresponsive warning happens a couple of time a year but every time, it’s frustrating. It prompts the message “A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete“.

I launched jskata not a long time ago and mostly talked about the undo feature. Now, I will talk about the jskata NoFreeze library to avoid freezing by splitting long processes into smaller ones.

You can look at the demo, the documentation or the source.

Old plain loop

This script loops the index variable from 0 to 1000000 and writes the current value in document.title. Unfortunately, it will freeze the page until the whole process is done.

  1. var index = 0; // index
  2. for(index = 0; index <= 1000000; index++) {
  3.     document.title = index;
  4. }

How to write a responsive for

I’m using jsKata.nofreeze library to avoid the freeze. This script will do the same as above. But, the page will remain responsive during the whole process.

  1. var index = 0; // index
  2. jsKata.nofreeze.forloop(
  3.     // the condition
  4.     function() { return index <= 1000000;  },
  5.     // the incrementor
  6.     function() { index++; },
  7.     // this is what will be executed
  8.     function fct() {
  9.         document.title = index;
  10.     }
  11. );

It uses closures to keep a resemblance to a good ol’ for loop.

Other loops : infinite and each

There are two other loops available. Infinite will loop indefinitely until you stop it. Each will loop through the properties of an object and loop in each one.

Take a look at the documentation to know more about them.

How to stop a process

As you see, every functions (forloop, infinite and each) return an object containing a stop function. So to stop a single process, just call it.

  1. var loop = jsKata.nofreeze.infinite(function() {//do nothing});
  2. loop.stop();

If you want to stop all the processes of a page, make this call :

  1. jsKata.nofreeze.stop();

More to come…

There’s much more you can do with that library but I wanted to keep it simple for this post. Next, I’ll talk about multi-process and other kinds of loop.

How to de-anonymize your anonymous functions

First of all, de-anonymized functions are called named functions and they look a lot like “regular” functions (in fact, they are).

Why should I de-anonymize?

For debugging. Instead of having a stack trace filled with ?() (representing an anonymous function), it is nicely printed and easier to follow.

For self-reference. Example, when you want an anonymous function to recall itself recursively, you would have to call arguments.callee. It’s odd and it’s deprecated anyway (people pointed to me that it’s not really deprecated but it throws an error in ECMAScript 5 strict).

Stack trace of anonymous functions…

If you run this in your firebug console (every javascripter should have firebug).

You get a stack trace that looks like this :
func()
func()
func()

… versus stack trace of named functions

You get a stack trace that looks like this :
f1()
f2()
f3()

As you can see, it’s a lot easier to debug and to understand who’s calling who.

Warning : There’s a bug in IE with named functions.

Recursive anonymous function

Let’s create a recursive anonymous function that counts to 10.

And let’s create it but using a named function.

Once again, the code is much clearer and it’s not using a deprecated element.

A note about closures to advanced javascripters

I just wanted to say that in the last example, you could have written this :

As you can see at line 4, I call the count function which is not the name of the function but the variable to which the function is assigned. It works, but it may not be the best thing to do. You can learn more about closure on that previous post and I’ll write more about it.

An undo/redo library for your app

I wrote about undo before and I pushed it farther. What about an undo/redo system? I extended the v.01 of the undo and I now handle undo and redo in the same object.

Annoucing redo in jskata.undo

I made a new version of jskata.undo still hosted on GitHub. If you look closer, it is now part of a library called jskata that is not officially announced. My next post will talk about it in details.

Demo

Take a look at the demo. The javascript of the demo is available here. You can see the complete doc on GitHub.

How does it work?

Execute an action that you can undo/redo

Doing something requires calling execute with 2 functions as parameters : the do and the undo.

Undo and redo the last action

Very easy!

Events and properties

For the moment, jskata.undo has just one event : onChange.

There are 2 properties : canUndo() and canRedo().

How to write a simple undo system for your app

I really like undos. If I could undo that that last beer… Unfortunately, I can’t. But, I can offer undo to users of my application.

When I thought about undo before, I thought about a complicated Rails plugin that would keep an anonymous ID linking to any table in the database with an “action” field that would contain the action to undo. Pretty complicated stuff for something as simple.

The javascript solution

One day while I was writing some javascript, the solution struck me : I could handle this completely with javascript. The basic idea is that whenever an action is completed, I can save its undo function in an array and call it whenever I need it.

Example, if I’m saving a user in a database with Ajax :

  1. I send the data to server to save a new user
  2. The server returns the ID of the new user
  3. I create a function with an ajax request that will send a delete of this user to the server
  4. I add the previous function to a stack of undo functions to be able to call it later

That, when I call that last function, it will undo that user creation without having to keep it in memory server-side.

Introducing jsKata.undo

I wrote a little something called jsKata.undo on GitHub that contains the logic describe earlier. It’s quite simple but it may grow over time. It has no requirement, not even jQuery. It’s very simple to use.

The complete doc is on GitHub.

1. Adding an action that can you can undo

I’ll use the “add a user” example with jQuery.

  1. $.post(
  2.   "http://yoursite.com/users/new", // The url to add a user
  3.   {name:"John Boucher"}, // The name of the user
  4.   function(newUser, textStatus, XMLHttpRequest) {
  5.     // This is called when the post is over
  6.     var newUserId = newUser.id;
  7.  
  8.     // We begin by creating a function to delete the user
  9.     var undoNewUser = function() {
  10.       $.post(
  11.         "http://yoursite.com/users/delete", // The url to delete a user
  12.         {id:newUserId} // The ID of the new user to delete
  13.       );
  14.     }
  15.  
  16.     // We add the undo function to the stack
  17.     jskataUndo.push(undoNewUser);
  18.   }
  19. );

2. Undo the last action you made

  1. jsKata.undo.undo();

3. Events

Each time there’s a change, an onChange event is called. To assign yours, simply write :

  1. jsKata.undo.onChange = function() {
  2.   // Show the undo button
  3.    $("#undoButton").show();
  4. }

There’s also an onEmpty event that is called when the stack of undoable actions is empty.

  1. jsKata.undo.onEmpty = function() {
  2.   // Hide the undo button
  3.    $("#undoButton").hide();
  4. }

Complete demo

There is a complete demo on GitHub as well as the HTML and Javascript code for it. Take a look!

How to write a singleton class in javascript

[UPDATE : This post is outdated. Check out the new post on singletons.]

If I look at my stats, a lot of people are wondering how to write a singleton class. I already wrote about it before but my old solution exposed the instance of the class so more than one instance could be created thus making it not completly a singleton class.

Here’s the new solution using a private variable for the instance.

How to create an object with private variables and methods

In short, you can use private variables when you return another scope when declaring a class.

  1. function Cats() {
  2.   var nameList = []; // private var
  3.        
  4.   // This is where you define another scope!
  5.   return {
  6.     add:function(name) {
  7.       nameList.push(name);
  8.     }
  9.   }     
  10. }

How does it work?

The magic lies in creating a different scope at the end of the class definition that does not include private variables. Then, private members are available in this scope and not outside of it, thanks to the power of closures.

Differences between private and public

These two classes definition shows the difference between the a class where all members are public versus a class where some members are private.

This is a class where all members are public.

  1. function PublicCats() {
  2.   // This is the list of cat names
  3.   this.nameList = [];
  4.  
  5.   // This is a method that I would like to be private but can’t
  6.   // It returns the last cat of the list
  7.   this.lastCat = function() {
  8.     return this.nameList[this.nameList.length-1];
  9.   }
  10.  
  11.   // Return the list of names
  12.   this.names = function() {
  13.     return this.nameList;
  14.   }
  15.  
  16.   // Add a name to the list
  17.   this.add = function(name) {
  18.     this.nameList.push(name);
  19.    
  20.     // Return the last cat just added
  21.     return this.lastCat();
  22.   }  
  23. }

This is the corresponding class where some members are private.

  1. function PrivateCats() {
  2.   // This is the list of cat names
  3.   var nameList = [];
  4.  
  5.   // This is a private method
  6.   var lastCat = function() {
  7.     // Note : I don’t use "this" to access private variables
  8.     // thanks to the power of closures!
  9.     return nameList[nameList.length-1];
  10.   }
  11.  
  12.   // These are our public methods!
  13.   // This is where we create another scope to
  14.   // avoid external objects to use the private variables.
  15.   return {
  16.     add:function(name) {
  17.       // Note : once again, I don’t use "this"
  18.       // to access the private variables and methods
  19.       nameList.push(name);
  20.       return lastCat();
  21.     },
  22.     names:function() {
  23.       return nameList;
  24.     }
  25.   }  
  26. }

In the above code, line 15 makes all the difference between the two classes.

On GitHub

Get all the code on GitHub and see it live in action on my GitHub page.

How to use JSON (updated with example)

This post is an update from the old post. A lot of things changed since it was written and the information in the old one is a bit outdated.

First of all, you should never use an eval() when using JSON because of security reasons that I will talk about later in another post. [edit : jQuery uses eval() but there's a work-around that will be talked about in another post.]

JSON and jQuery

The simplest way to use JSON is though jQuery. I have been using for more than 2 years and I never was disappointed.

Let’s say I want to call Flickr search with JSON. It’s simple :

  1. $.getJSON(
  2.         "http://api.flickr.com/services/rest/?jsoncallback=?",
  3.         { method : "flickr.photos.search",
  4.                 api_key : "4ef2fe2affcdd6e13218f5ddd0e2500d",
  5.                 format : "json",
  6.                 tags : "landscape",
  7.         },
  8.         ajaxCallBack
  9. );
  10.  

The $.getJSON takes 3 parameters.

1. The URL
The URL of the remote call.

2. The parameters
The parameters to complete the call. On the documentation page about this Flickr method, you have a list of all the parameters you can use. For a JSON call on Flickr, you have to send the api_key and the format. I added the parameter tags to send me all photos that are tagged landscape.

3. The callback
Most API services now requires a callback, a method that will be called when the JSON is loaded. It is more secure and easier to work with. At the end of the first parameter (the URL), I added jsoncallback=? (flickr called this parameter jsoncallback but it could be named differently on other services). This is the jQuery-way of saying “When you finish loading the JSON, call the method specificied by the third argument”.

You may wonder how Flickr knows which function to use on callback. It’s because in jQuery, there’s a special case for that. In the URL, you can see that the jsoncallback is written like that jsoncallback=?. The ? is replaced by your own callback method (in my case, I called it ajaxCallback)

The callback method

The callback method I used looks like this :

  1. function ajaxCallBack(data) {
  2.         // Loop throught all photos and display them
  3.         // it uses the jquery.each method
  4.         // doc at http://docs.jquery.com/Utilities/jQuery.each
  5.         $.each(data.photos.photo, function(photoIdx, photo) {
  6.                 // Build the thumbnail url
  7.                 var thumb_url = ["http://farm", photo.farm, ".static.flickr.com/",
  8.                         photo.server, "/", photo.id, "_", photo.secret, "_t.jpg"].join("");
  9.                
  10.                 // Build the photo url
  11.                 var photo_url = ["http://www.flickr.com/photos/",
  12.                         photo.owner, "/", photo.id].join("")
  13.  
  14.                 // Build HTML
  15.                 $("body").append(
  16.                         $("<a>")
  17.                                 .attr("href", photo_url)
  18.                                 .attr("target", "_blank")
  19.                                 .append(
  20.                                         $("<img>").attr("src", thumb_url)
  21.                                 )
  22.                 )
  23.         });
  24. }
  25.  

If you know jQuery a little, it simply creates the HTML to show the thumbnails and a link to the photo.

Get the code

You can get the complete code for this example on GitHub and a working example.

How to have jQuery and prototype.js in the same project

I’m a big fan of jQuery. This librarie is just the best and simplest one around. I really noticed it when I wanted to get rid of jQuery in TimmyOnTime and try to use prototype.js instead, just to be more “rails-oriented” (that’s a pretty lame excuse don’t you think?)

Why I didn’t like prototype.js

There was not a lot of javascript written for the project so I thought that getting rid of jQuery and using prototype.js would be easy. It turned out to be hell on earth. Prototype.js made me feel like I was back in the 90s writing C++. A simple click event turns out to be a awful lot of ugly code with ugly function names.

Example, if I wanted to show the content of a DIV I clicked in prototype.js, I would use things like Event.observe, bindAsEventListener, a mix of native DOM element and prototype.js element, and worst of all, an unintelligible documentation.

jQuery as a complete different way of doing it in a single easy-to-understand line :
$(“#a_div”).click(function() { alert($(this).text()); });.
As simple as that!

The problem

I wanted to use some interface element in Rails that requires prototype.js so I had to have both librairies. The problem is that there’s a conflict between them. Prototype.js doesn’t seem to give a damn about it but jQuery is nicer with you. It offers a noConflict method.

With Rails, prototype.js is the default librairie so to override this, you could do

  1. <%= javascript_include_tag "prototype", "jquery" %>
  2. <script>$j = jQuery.noConflict();</script>

This way, you will have to use $j instead of $ to call jQuery.$ would still call prototype.

Another thing you could do is to use jQuery on Rails and don’t give a damn about scriptaculous. I personally prefer to use librairies that are fully tested instead of using a “by-pass” that could break my code. It’s your choice…