Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Stackoverflow binds user actions dynamically with javascript?

Checking the HTML source of a question I see for instance:

<a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript>&nbsp;JavaScript is needed to access comments.</noscript>

And then in the javascript source:

// Setup our click events..
$().ready(function() {    
        $("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); });    
});

It seems that all the user click events are binded this way.

The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly?

like image 710
Santiago Corredoira Avatar asked Sep 28 '08 08:09

Santiago Corredoira


4 Answers

  • You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug)
  • You can hand over the HTML/CSS to a designer who need not have any javascript skills
  • You have programmatic control over what callbacks are called and when
  • It's more elegant because it fits the conceptual separation between layout and behaviour
  • It's easier to modify and refactor

On the last point, imagine if you wanted to add a "show comments" icon somewhere else in the template. It'd be very easy to bind the same callback to the icon.

like image 117
Dave Nolan Avatar answered Nov 18 '22 18:11

Dave Nolan


Attaching events via the events API instead of in the mark-up is the core of unobtrusive javascript. You are welcome to read this wikipedia article for a complete overview of why unobtrusive javascripting is important.

The same way that you separate styles from mark-up you want to separate scripts from mark-up, including events.

like image 44
Eran Galperin Avatar answered Nov 18 '22 20:11

Eran Galperin


I see this as one of the fundamental principals of good software development:

The separation of presentation and logic.

HTML/CSS is a presentation language essentially. Javascript is for creating logic. It is a good practice to separate any logic from your presentation if possible.

like image 2
Dan Herbert Avatar answered Nov 18 '22 18:11

Dan Herbert


This way you can have a light-weight page where you can handle all your actions via javascript. Instead of having to use loads of different urls and actions embedded into the page, just write one javascript function that finds the link, and hooks it up, no matter where on the page you dump that 'comment' link. This saves loads of repeating html :)

like image 1
SchizoDuckie Avatar answered Nov 18 '22 20:11

SchizoDuckie