Archive for the ‘technical level’ Category.

How to use the self with object-oriented javascript and closures

When I began with object-oriented javascript, I always saw a self here and there without fully understanding what it meant.

Self?

When you see self in some object-oriented javascript, it’s just mean that the developer is using a closure that will reference the current object via a variable named self. Because self is a variable, it could be named anything else. The use of “self” as a name is a unwritten convention but it could be whatever you want.

  1. // Create a cat
  2. function Cat() {
  3.     this.theCatName = "Mistigri";
  4. }
  5.  
  6. // The cat will meow later
  7. Cat.prototype.meowLater = function() {
  8.     // I create the variable self that refers to the this (the current object)
  9.     var self = this;
  10.  
  11.     // I create a timeout that calls the self.meow function within an anonymous function
  12.     /*** NOTE : You don’t always have to create an anonymous function it’s just that in
  13.         this case, it is required ***/
  14.     window.setTimeout(
  15.         function() {
  16.             self.meow();
  17.         }
  18.         , 1000);
  19. }
  1. // The cat meows
  2. Cat.prototype.meow = function() {
  3.     // I can use the this expression!!!
  4.     alert(this.theCatName + " : meow!");
  5. }
  6.  
  7. // I crate an object and call the meowLater() function
  8. var theCat = new Cat();
  9. theCat.meowLater();

Why not use the this?

Because when using closures within an object, the this in the called function (in the above example, in the meow() function) is the window object.

Our last project : Ecstatik!

Frank (of Ruby Fleebie) and I have been busy lately. We worked together on a project called Ecstatik!

What is Ecstatik!?

Ecstatik! is a project that caused Frank and I to be busy lately. But it’s not just that.

Ecstatik! is a digg-like for funny stuff. No more than that. We didn’t want to make the world a better place, we wanted to have a common project and get it done. A project that would break the classic cycle of “I have a project and it will be big” and ends up in a black-hole somewhere in the universe.

For the moment, there’s no fancy features. Not even a good looking design. These things will come one day but the main idea is keep it simple, stupid. This is an overheard expression but an underused one. I think that this time, we’ve done it.

How is it done?

Ecstatik! is all Rails. It was my first time and I rediscovered how pleasant could be the server-side development. I worked with PHP a lot recently and was bored of it. It is so redundant. Create an object. Write a form to create/edit the object. Write SQL to handle this object. Write some more SQL to work with objects that are linked. I hate that! Rails does all that redundant work for you and if you want, you can modify or optimize it without being restricted. This is the way life for a developer should be.

Don’t hesitate and go for Rails!

The javascript side

I didn’t write a lot of javascript because I wanted learn as much as possible about rails. For the voting process, I used ajax/json via JQuery. This javascript library is simply amazing.

  • The selectors combine javascript, css and xpath. It is the most complete HTML object selection ever seen by human.
  • The manipulation of HTML object are easily modifiable.
  • The ajax support offers all we could want of ajax.

Take a look at ecstatik! and have fun!

How to use JSON

UPDATE : This was written more than 2 years ago, read the new post on How to use JSON.

Web2.0 came with the intensive use of the XMLHttpRequest object even if it was already in our browser before then. A lot of format were tried but JSON will be the winner overall.

What is JSON?

JSON is a format for communication between the server-side (PHP, ASP.NET, …) and the client-side (javascript). The magic of it is that the response from the server-side can be easily converted to an object via the use of the eval() function.

Eval() is a function that gives you the possibility to execute some code in javascript from a string.

  1. eval("alert(‘This is from eval()’)");

This is a bad idea to use it in your code but so easy for JSON that you have to use it.

How to JSON on the server-side?

You can work like an idiot and create your own JSON marshaller for your project or you can go to json.org and use one of the objects that you can find.

I’ll take PHP as example. You want to send an object to javascript. You simply do

  1. $response = array();
  2. $response["id"] = 3;
  3. $response["message"] = "The object was saved";
  4. echo(json_encode($response);

It will echo

{id : 3, message : "The object was saved"}

How to JSON on the client-side?

Use the eval() function.

  1. var json = eval(theServerSideJsonTextResponse);

You can now use the json variable created like this

  1. alert(json.id + " : " + json.message);

and it will alert

3 : The object was saved

Beware!
There may be an invalid label error here. The solution is to add parenthesis to the response.

  1. var json = eval("(" + eval(theServerSideJsonTextResponse); + ")")

#UPDATE : May 10, 2007
As it was pointed out in the comments, you should never use eval directly when parsing JSON on the client-side. Use a existing JSON parser or a library (jquery is my favorite).

Other formats

For sure there are hundreds of ways of sending back a response to javascript but to my experience, JSON is the best. Let’s take a look at the others.

XML is for purists with a lot of time to spend
Do you really want to write a XSD (or DTD) for all the calls that can be made to the server? Anyway, it’s long to develop because you have to parse it all.

HTML is for lazy people
Though it’s not completly wrong, laziness is often a bad thing. What do you do if you want to reuse information that you got in a HTML? You parse the HTML to extract the info? please don’t…

CSV is for the people that are stuck in the 90s
CSV was the coolest thing back in the 90s along with Fresh Prince of Bel-Air.

Watch out for BISON

BISON is nothing else than Binary JSON (see this article). It’s lighter than JSON but still unstable. My guess is that we’ll all use it sooner or later… but it’s just a guess…

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!

How to execute javascript code directly in your browser

This trick is not known by everyone though it is really simple.

The address bar

In the address bar, you simply write

  1. javascript:/*some javascript code here*/;void(0);

As easy as that.

In fact, it’s the same thing as creating a link that executes some javascript code.

  1. <a href="javascript:alert(‘Some code from a link’);">Execute code from javascript</a>

The only thing I add is the void(0); at the end of the code to avoid a “bug” that reloads the page.

Hey, if you want to write a bookmarklet, you’ll probably use this technique.

Firebug

These days, you can’t write javascript without using Firebug (apart if you are a javascript magician). You just can’t. For the ones who don’t know Firebug, I’ll describe it in 7 words : javascript debugger, html inspector, css modifier, fun.

On the “Console” tag, there’s one line beginning with “>>>” at the bottom. This is the javascript executer. If you click the red arrow at the end of the line, you have a multi-line executer.

I always use it to write and test the javascript snippets on this site.

What can I do with that?

Everything you want. In fact, I use it for these purpose :

  • write code snippet for Javascript Kata
  • write a bookmarklet
  • debug javascript on Firefox
  • have fun on other’s sites

Mastering the date object in javascript

Javascript has a pretty basic Date object. It is cool but not as cool as in other languages. In fact, it is different but we like it anyway.

The primitive value

A date is nothing else than the number of millisecond since January 1, 1970 00:00:00. So now is 1 177 603 737 358.

When you create a Date object, it is initialized at now. To alert the primitive value (the number of milliseconds since 1970), I simply do.

  1. var now = new Date();
  2. alert(now.valueOf());

Adding and subtracting

Note : You have to know that months in javascript are 0 = january and 11 = december. Just like Java.

This one is easy. When I want to add a number of days (or anything else) to a date, I use the getDate() and setDate() function. When you don’t know that the setDate() function (and setHours, setMinutes, setMonths…) has some magic in it, you may have a hard time manipulating the dates.

So, I want to add 3 days to the current date.

  1. var now = new Date();// Add 3 days
  2. now.setDate(now.getDate() + 3);
  3. alert(now);

The problem is when you want to add 3 days to December 31 2006, it should return January 3 2007. No problemo!

  1. var now = new Date();
  2.  
  3. // Set to December 31 2006
  4. now.setYear(2006);
  5. now.setMonth(11);
  6. now.setDate(31);
  7.  
  8. // Add 3 days
  9. now.setDate(now.getDate() + 3);
  10.  
  11. alert(now);

You see that the date is correctly computed. You can do the same things with all the other parts of the date. Magic is in the air!

No formatting

There’s no way of formatting a date to a string except if you use concatenation.

If you want to display the YYYY-MM-DD format, you’ll have to do this ugly code.

  1. var now = new Date();var nowStr = now.getFullYear().toString() + "-" +
  2.     (now.getMonth()+1 < 10 ? "0" + (now.getMonth()+1).toString() : (now.getMonth()+1).toString()) + "-" +
  3.     (now.getDate() < 10 ? "0" + now.getDate().toString() : now.getDate().toString());
  4.  
  5. alert(nowStr);

Maybe you won’t do it as ugly as this but it won’t look pretty. Maybe you should check for a librairy.

The Date.parse() function

Don’t use the Date.parse() function. I don’t even know which format it takes. It looks like month[sep]day[sep]year but I’m not sure. Better use some regexp and use the set[DateUnit]() function accordingly.

getYear() VS getFullYear()

You should not use the getYear() function. For an obscure reason, it returns the number of years since 1900. You don’t want to use it. Trust me.

You are now a master

That’s what you need to know about javascript Date object, you are now mastering it.

Do you have something else to add?

Do not use javascript for validations

This one will be widely accepted. The problem with it is that it’s so obvious that the question is asked here and there.

Javascript is not secure

I repeat : javascript is not secure. Your code is readable and it can be modified by anyone. It is great when you want to do a bookmarklet. It is not so great when you want to have a hard as a rock web application.

Example, you want to validate that a manually entered date is less than today. The javascript code for it is not complex.

[source:javascript]
function validateDate(theDate) {
var now = new Date();
return (theDate < now);
}
[/source]

But anyone could override the function to always return true and all the dates that he enters would be good. This is bad.

Always validate on the server-side

Whenever you have to validate something in your web application, use the server-side. I know, it is redundant and long to do but you must do it. Someone once said that you must consider every input from the user has evil.I prefer the word dirty. Users sometimes don’t want to be evil to a web application but they are. And sometimes, users want to be evil.

If you have little time to implement an application, just do the server-side validations.

You must consider javascript validations as “pretty” validations. It validates things but it just to make your application prettier. In facts, it helps you with usability and it simplifies the life of the users of your application.

The “cheap return” method

To avoid to write a lot of code on the server-side for validations, I would suggest you a simple method that will help you code faster. It is called the cheap return method.

  1. You do all the validations on the client-side in javascript.
  2. You do all the validations on the server-side but if it fails, you display a generic page to the users that says that it has failed.
  3. You pretend to have done it completly on the client-side and server-side.
  4. You spend the rest of your time watching the ceiling.

The idea behind that is that if all javascript validations have passed, the users must have done something between the client-side and server-side. So, he is responsible of that error.

I don’t really like it either…

The problem with bookmarklet

I talked earlier about bookmarklets and how wonderful they are. In today’s web2.0 world, you can’t have a successful application without giving your users a cool bookmarklet. It can be easy to do sometimes (like the one of del.icio.us) but you always want to do more and it gets more complex… until the day you hit the wall

The problem

You can’t execute code without a click of the user. It is obvious to 99,42% of you, but there will be a day when you’ll just say “I want to execute some friggin’ code without a click from the user”. Even if you want to do it to simplify the life of the user, you can’t. There must be a solution.

The solution

For now, the solution is called GreaseMonkey. This is a Firefox add-on that executes javascript automatically when certain pages are called.

Example, I want every background color of every web page I visit to be gray. I would create a script with this code


document.body.style.backgroundColor = "gray";

and it would just work.

The problems of the solution

It is Firefox only. With around 75% market shares, Internet Explorer just can’t be forgotten.

It is too complex
. The user has to know how to install add-ons and how to install greasemonkey scripts. It is way to hard for a normal user.

The real solution

I don’t have one and that’s why guys that I ask you : how to execute javascript code automatically without a click from the user?

I want all the solutions you can give to me wether it is real or fantasy.

Thanks alot!

How to do a bookmarklet with javascript

The day I discovered it, I was really happy. Not happy as a fish in water but maybe happy as a cat having its meal (though it enormously depends of which cat we are talking about). Talking about bookmarklet to some of my friends, I saw that there were a lot of incomprehension about it. So I’ll begin at the beginning.

What is a bookmarklet?

A bookmarklet is a chunk of javascript code that can be added as a bookmark in your browser. When you click the bookmark, the javascript is executed. This can do a lot of things.

To add a bookmarklet, simply drag the link into your bookmark toolbar.

Why does it work?

It works because when a page is loaded in the browser (the client), it has complete power over it. Using javascript, you can do whatever you want without being stopped by some kind of security. Isn’t it wonderful?

How to do a bookmarklet

1. Write some javascript that does something useful
2. Put it in a link with the command javascript: before it and void(0); (just to be safe) after it
3. Tell the people to drag the link in their bookmark toolbar

I have to say that the javascript code has to be less than 2083 characters, the limit of characters that enters in the address bar in Internet Explorer.

How to import another JS in a bookmarklet

You want to have a complex “application” executed on a page but you can’t do it in less than 2083 characters? As I said earlier, the client has the complete power over the currently displayed page so you can import javascript files in the current page.


var script = document.createElement("script");
script.src="http://www.example.com/javascript.js";
document.body.appendChild(script);

Now, put that on one line add javascript: at the beginning and void(0); at the end and you’re set.

Now, let your creativity flow and make a great application.

Do not use the innerHTML property on HTML objects

I already said Do not use the style property on HTML objects and as I was thinking how bad the innerHTML property can be, I considered doing an article on that subject. The problem was that stones were thrown at me after the first “Do not” article. Now I fear that this one may be worst… but I’ll stand proud…

innerHTML seems easy

I like easy things : Diner Kraft and automatic cars. It’s so easy to write HTML, why should I spend time with the DOM when I can easily do it with innerHTML?

With the Dom
[source:javascript]
var aLink = document.createElement(“a”);
aLink.href=”http://www.javascriptkata.com”;
aLink.appendChild(document.createTextNode(“Javascript Kata”);
document.body.appendChild(aLink);
[/source]

VS with innerHTML

document.body.innerHTML += "<a href=\"http://www.javascriptkata.com\">Javascript Kata</a>";

Why???

innerHTML is dirty

It may look good at first sight but it’ll look real bad the next morning without make-up. Did you noticed the \”? Prepare yourself because with innerHTML you will have a truck load of these. Take a look at this.

document.body.innerHTML += "<a href=\"http://www.javascriptkata.com\" id=\"theLink\" class=\"aLink\" title=\"Javascript\">Javascript Kata</a>";

Ouch! My eyes burn.

A lot of HTML

iInnerHTML looks worst if you have a lot of And now, what if you have a lot of HTML code embedded in your javascript, it will win the war over you. I tell you.

innerHTML and ajax

I have an idea, if my ajax request returns some HTML, I could use the innerHTML property on an HTML object and assign the ajax response to it and it would be magic!

NO! In fact, you can do it but for every reasons in the world, don’t ever do that. Yeah, I know, Yahoo!TV is doing it but don’t fall in that trap.

Ajax should return data to your application. Why? Because you’ll never know what you’ll have to do with that information. For the moment, maybe you just do a simple display of the data but sooner or later, you’ll have to re-use for another section of the page. If you return HTML, you will end up parsing it to extract the data contained in it. I tell you.

By the way, forget about that old XML thingy, try JSON

It is not standard

It doesn’t really matter to me but if you’re a W3C-compliant kind of guy, that may be a good point.

Your friend is a library

You have a lot a HTML code to produce through you javascript, go and get a good library. I can’t tell you which one to use because they all have the ups and downs. Choose one and stick to it.