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.

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.

Easy loop for every element of an array

There’s something bugging me with javascript for loop : the extra work to loop though all elements of an array. Suppose I want to alert each element of an array, there are three ways of doing it.

First, you loop with an index and assign the element to a variable.

  1. var items = ["a", "b", "c"];
  2. for (var i = 0; i < items.length; i++) {
  3.   var item = items[i];
  4.   alert(item);
  5. }

You always have to have that extra assignment at the beginning of the loop.

Second, you loop with a for each.

  1. var items = ["a", "b", "c"];
  2. for (var i in items) {
  3.   var item = items[i];
  4.   alert(item)
  5. }

In javascript, the for each loops though the index of the array instead of looping though the elements, like in most other languages. Thus, you also have to make the extra assignment at the beginning of the loop.

The easiest way of doing it is the third one.

  1. var items = ["a", "b", "c"];
  2. for (var i = 0, item; item = items[i]; i++) {
  3.   alert(item);
  4. }

How does it work? First it uses multi-assignment on one line. In javascript, you could write var i = 0, j = 1; and it would create two variables, i and j.

The second part of the for is confusing : it assigns the item but it never check if i it is out of bounds of the array (using i < items.length). It works because when javascript tries to assign an item after the end of the array (in our case items[3]), it returns null which is considered by javascript as false.

Be ahead of the trend, try CouchDB

I always loved and hated databases. When I was a younger programmer, I asked to switch to DB administrator and, thank God, they didn’t agree to let me mutate in a DBA. I ended up fired like 80% of the company (except the DBA). In fact, I wanted to be DBA because I thought I knew how to work with a DB better than them. The rest of my life proved me wrong. Nobody knows what they’re doing because relational databases are a mess.

Then came the non-relational database. Amazon’s SimpleDB was the first NRDBMS (as opposed to RDBMS) that got a public attention. When I read the specs, I really thought it was cool but I wondered “Is it scalable?”. Then I remembered that there is no such thing as a scalable database. Databases need to be smashed and hurt in order to be as scalable as we want them to. I wanted to give it a try but I wasn’t ready to pay for it yet.

Working with xmpp/jabber, I saw a post by the well-known metajack (his blog is mainly about xmpp) about couchdb and I knew the time as come for me to be different. I had to try it so I opened a terminal and wrote sudo apt-get install couchdb. This was the beginning of a great adventure for me…

What’s the link between CouchDB and Javascript? CouchDB is completly JSON. You can write an application that is completly JSON/Ajax without a single line of PHP/Ruby/Python/whatever.

I’m currently writing a simple app for CouchDB and this is the first of some posts about writing an app with CouchDB. I currently use version 0.8.0 and I ran through a lot of problems and I wish these posts will help you succeeding in building an application supported by CouchDB without all the hassle I went through.

Because my main project is TimmyOnTime (and don’t forget to check out our new blog behind the clock), I will work partial-time on this project so it might not go as fast as I (and you) want. But don’t despair, you will still be ahead of the trend when NRBDMS will go mainstream.

Cleanest way of executing javascript code on page load

Everytime that I work on a new project, I’m always unsure about which way to execute javascript on page load. These are the different techniques :

Your old buddy body.onload()

The safest way to execute javascript when a page loads is to use the body.onLoad method.

  1. <body onload="doSomething();"></body>

The document.ready function with jquery

This technique requires jquery and is similar to the body.onLoad technique (see above).

  1. <body><script>$(document).ready()</script></body>

The problem is that I don’t like that the javascript code is too close to the HTML code. There’s really something that I don’t like.

The #ID.ready

DO NOT USE! It doesn’t work. At first, I tought that this technique worked but in fact, even if the element corresponding to the ID doesn’t exists, the function is called. To understand it better, I’ll give you an example. Suppose that I want to load a user list with ajax after the page load and that list correspond to ul#users, I’d write the following code

  1. $("ul#users").ready(function() {
  2.   loadUsersWithAjax();
  3. });

Unfortunately, it doesn’t work.

The document.ready + #ID.each

After the failure of the #ID.ready technique (see above), I tried a similar thing that is working but ugly looking. Suppose I want to do the same as above, I’d write this :

  1. $(document).ready(function() {
  2.   $("ul#users").each(function() {
  3.       loadUsersWithAjax();
  4.   });
  5. });

That way, it would execute the loadUsersWithAjax() method for each ul#users and because element IDs are unique to a page, the method would be called only once. It looks bad but it’s the “prettiest” way I found of executing javascript code on page load.

Now, I want to know what would you suggest? Which technique is your?

JavascriptKata now ad free

[Update 2009-09-20 : I will try to bring back ads. I removed them because I was frustrated, I bring them back as an experience.]

JavascriptKata was created in the blog bubble. In a time when all you had to do was to create a blog, put ads on it and you were rich. It never was true. The ads on this blog gave me about 100$ in a year so I finally felt discouraged and left it for dead. Nevertheless, this blog as a good share of traffic and more subscribers in the feed than any blog that I’ve owned/I own/will own. In fact, I call it a blog but it’s not really a blog. I used wordpress and that’s the main reason why I’m calling it a blog.

I tried several things to keep my interest in writing about javascript but they all failed because there was the devil saying “anyways, you don’t make any money out of it”. But there was the angel saying “maybe you don’t make money but you like javascript and should continue to write about it”. As usual, the devil won.

I won’t try to make another revival of this blog but I’ll try to write more about little things that happens between me and javascript, about the daily problems that I encounter. I’ll write a lot about jquery too since for me, there can be no javascript without jquery.

Thanks to all of you!