Archive for the ‘technical level’ 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().

Error with hashes in IE but not in Firefox

There’s a common error that happens quite a lot on IE only and never on Firefox. You search it, you check all your variables, you comment your code to the bare minimum but you can never find it.

Stop looking! Here’s the answer.

You probably just forgot a comma (,) at the end of a hash. Here’s an example :

  1. var val = {
  2.   cat:"Mistigri",
  3.   dog:"Rex",
  4.   butler:"Jeeves", // There’s an extra comma
  5. }

You see the extra comma at the string “Jeeves”? This what causes the problem. Firefox handles an extra comma nicely but Internet explorer doesn’t. To correct the error, just write :

  1. var val = {
  2.   cat:"Mistigri",
  3.   dog:"Rex",
  4.   butler:"Jeeves" // There’s no extra comma
  5. }

JSLint to the rescue

Programmieraffe told me about JSLint. You paste your javascript code and it verifies it for you. Not only for extra-commas but everything else.

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!

Two google-like jquery calendars

Sometimes, it feels to me that javascript was invented for the only purpose of writing calendars to select a date. I wrote one myself (because I had to, not because I wanted to) in a previous job. I use a new calendar that is “better than the other one” on each of my project. It seems like the world will never run out of javascript calendars. In fact, you probably are writing a new one as you read this.

I want to talk about a different kind of calendar. The really hard one to write : calendars for displaying events in jquery.

The pretty jquery-week-calendar

Written by Rob Monie, this is the first one I tried. I was amazed about how easy it was to integrate with the current development of Timmy (you can see an early beta when you’re logged here). You can take a look at the demo. Unfortunately, I had unexplicable bugs and I didn’t take the time to understand them. Please, don’t do like me and participate to the code on GitHub.

  • Looks good
  • Easy to integrate
  • May be buggy when drag-dropping/resizing

The robust fullcalendar

We switched to this calendar, written by Adam Shaw, because it had three different views (month, week, day) and because we had some problem with the other calendar. It doesn’t look as good as the week-calendar (demo). You can also participate on GitHub.

  • The default look is OK
  • Harder to work with
  • Display may seem slow (on firefox)
  • More robust than week-calendar

Finally

These guys have made a great job doing something really hard. Just think about two overlapping events or when an event is two minutes long or hundreds of special cases that could happen. Kudos to them for giving their time and talent to us.

A word about git

Our team (me and Frank, the RubyFleebie guy) worked with SVN for a couple of years until Git stole the spotlight. For a couple of months, we worked with it and enjoyed it. Until we had to do “more advanced” things (branching, merging which is pretty basic to my sense) and things got incredibly hard. We switched to Mercurial a couple weeks ago which feels more like the perfect mix between SVN and Git. So if, like us, you feel puzzled by Git, give Mercurial a chance.

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.