Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to add an event in JavaScript?

I see 2 main ways to set events in JavaScript:

  1. Add an event directly inside the tag like this:

    <a href="" onclick="doFoo()">do foo</a>

  2. Set them by JavaScript like this:

    <a id="bar" href="">do bar</a>

and add an event in a <script> section inside the <head> section or in an external JavaScript file, like that if you're using prototypeJS:

Event.observe(window, 'load', function() {
    $('bar').observe('click', doBar);
}

I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).

The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.

Which method is the best?

A killer answer will be fully appreciated!

like image 683
paulgreg Avatar asked Aug 29 '08 07:08

paulgreg


2 Answers

I think the first method is easier to read and maintain

I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control.

Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you don't have to search for all places making a call to a function, you simply have to change it in one place. When adding more elements that should have the same functionality you don't have to remember to add the handlers to them; instead, it's often enough to let them declare a class, or even not change them at all because they logically belong to a container element of which all child elements get wired to an action. From an actual code:

$$('#itemlist table th > a').invoke('observe', 'click', performSort);

This wired an event handler to all column headers in a table to make the table sortable. Imagine the effort to make all column headers sortable separately.

like image 74
Konrad Rudolph Avatar answered Nov 07 '22 04:11

Konrad Rudolph


In my experience, there are two major points to this:

1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.

2) The second kind, i.e. Event.observe() has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.

like image 33
Thomas Lötzer Avatar answered Nov 07 '22 04:11

Thomas Lötzer