Archive for the ‘function’ Category.

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.

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 do a non-destructive overwrite of a function in javascript

I really don’t like the “non-destructive” expression but I couldn’t come up with a better one.

What?

You want to create a function but you will overwrite the old one. You just want to add some code before or after it.

Example, you create a javascript applet that can be added to web sites you do not own and you want to call a function in the body.onclick() event. Maybe the site already has something in the body.onclick() event and you don’t want to overwrite it because the other developer will be mad at you. You’re stuck!

How?

First of all, don’t panic. Take a deep breath and relax.

Now, you’re ready.

  1. var oldBodyOnClick = body.onclick;
  2. body.onclick = function() {
  3.         // Add your code here!
  4.         alert("Before the old event");
  5.  
  6.         if (oldBodyOnClick != null) {
  7.                 oldBodyOnClick();
  8.         }
  9.  
  10.         // or here!
  11.         alert("After the old event");
  12. }

Could you repeat slower please?

Ok.

First, I assign the body.onclick() event to a new variable.

  1. var oldBodyOnClick = body.onclick;

Second, I create a new function that will be called on the body.onclick() event.

  1. body.onclick = function() {

Third, I add code before the old event

  1. alert("Before the old event");

Fourth, I call the old event if it is not null

  1. if (oldBodyOnClick != null) {
  2. oldBodyOnClick();
  3. }

Third, I add code after the old event

  1. alert("After the old event");

That’s it!

The power of closures in javascript

Now is the time. I can’t go forward if I don’t talk about closures. What are closures? Closures are your friend. That’s the first thing you need to know about them. They will help you keep your code clean, healthy and easy.

A closures is created every time you create a function in a function (they are also created in other situations too but I won’t talk about them now). When using a closure, you will have access to all the variables defined in the parent function (and all its parent functions too).

Attention! Before reading this article, you should take a look at 3 ways of creating functions in javascript.

Write your first closure

  1. function function1() {
  2.         var var1 = 1;
  3.  
  4.         // Magic here! I create a function inside another function
  5.         function function2() {
  6.                 var var2 = 2;
  7.  
  8.                 // I have access to var1 defined in function1
  9.                 //(the parent function of the current one)
  10.                 alert(var1 + var2);
  11.         }
  12.  
  13.         // Call function2
  14.         function2();
  15. }
  16.  
  17. // Call function1 (should alert 3)
  18. function1();
  19.  

For the moment, it doesn’t make sense but you will surely find a handy way of using it.

Example of a closure

Example of a closure, I want to alert the ID of the timer (returned by window.setTimeout) after 1 second.

In an old-fashioned (without closures) way, I would do the following.

  1. var globalTimer = null;
  2.  
  3. function createTimer() {
  4.         // I create the global timer
  5.         globalTimer = window.setTimeout(alertTimerId, 1000);
  6. }
  7.  
  8. function alertTimerId() {
  9.         // Alert the global timer ID
  10.         alert("The timer ID is " + globalTimer);
  11. }
  12.  
  13. createTimer();
  14.  

There are many problems with that code. The most obvious one is : it uses a global variable. You never know what happens to global variables between the time it is instantiated and the time it is used. It’s bad.

In a new-fashioned (with closures) way, you would do this.

  1. function createTimer() {
  2.         // I create an inner-function that alerts the timer ID
  3.         function alertTimerId() {
  4.                 // I call the "timer" variable from the parent function (using closures)
  5.                 alert("The timer ID is " + innerTimer);
  6.         }
  7.  
  8.         // I create the timer
  9.         var innerTimer = window.setTimeout(alertTimerId, 1000);
  10. }
  11.  
  12. createTimer();

I have solved the global variable problem.

Now, what can I do?

Because closures are not implemented in every programming language (update : though it is not specific to javascript), you’ll have to try it for yourself. I don’t want to give you recipes on how/when to use it, it’s up to you. But I could say that a great ajax web2.0 application normally uses a lot of closures.

Keep in mind that
- Closures are created everytime you create a function in a function
- Closures give you access to variables that are defined in the parent function (and all of its parents)
- A closure keeps a reference to an object, not a copy (more on that later)
- Watch out for memory leaks in Internet Explorer!!!

3 ways of creating functions in javascript

In javascript, all functions are an instance of the class Function (with a capitalized F).

The old way

Everybody knows how to do it. In fact most languages do it this way. Boring but you can’t write javascript without knowing it.

[source:javascript]
function f() {
}
[/source]

The uppercase F way

You can directly create an instance of the Function class this way.

[source:javascript]
var f = new Function(“alert(‘Function called’);”);
f();
[/source]

The problem with that is that the code of the class is passed as a parameter of the constructor. A lot of people use this method to create “dynamic” functions but they do just because they don’t know of the lowercase f way of doing it.

[source:javascript]
var i = 100;
// “dynamically” alert the i variable
var alertNumber =new Function(“alert(‘Number is ” + i + “‘);”);

alertNumber();
[/source]

It looks bad for such a simple example. It gets uglier as it gets more complex. Please, don’t use this method.

The lowercase f way

This one is the one you’re looking for. Why? Because it is as handy as the uppercase F but you don’t have to write the code as a string. Example, I dynamically load an image and I want to alert when the image is ready.

[source:javascript]
var img = new HtmlImage();
img.src=”…”;

var onLoadFunction = function() {
alert(“Image is ready!”);
}

img.onload = onLoadFunction;
[/source]

But wait!

As I was writing this, I realized something that I didn’t realize before. The old way of writing functions is not as boring as I thought.

[source:javascript]
function parent() {
function child() {
alert(“Child function called”);
}

// Assign the function to a variable
var childFunction = child;

childFunction();
}

parent();
[/source]

Executing above code will alert “Child function called”. So, javascript also creates a variable called child when I write function child() {}. Interesting.