views:

313

answers:

2

I heard Ryan Bates say that the Rails JavaScript helper methods prevent "unobtrusive JavaScript".

Is this correct and, if so, could someone explain why?

+2  A: 

Unobtrusive just means "Don't mix your HTML with your javascript behavior". Another way to say this is "Don't change your HTML just because you want to use javascript". The rails javascript helper methods do just that in a kind of hidden way.

Say you weren't using javascript at all. If you wanted an HTML form you'd use form_for and have a regular form. Now say you want to add javascript so that your form submits an AJAX request instead of a regular HttpRequest. You have two ways to do this.

  1. You can use the helper method remote_form_for
  2. You can use something like jQuery to bind a function to the submit call that submits your form via AJAX.

The first method is obtrusive. You're changing your markup (look at the generated code). The second method is unobtrusive. By using jQuery and attaching the behavior from javascript you don't alter your HTML at all.

Jason Punyon
Good explanation. Thanks.
@Lee Tang: Always happy to help :)
Jason Punyon
A: 

the rails helpers add the onclick events right into the html. i always thought unobtrusive meant that your page will still work when a user has javascript disabled, but after jason punyon's answer popped up while i was typing, i checked into it.

indeed the technique to completely separate javascript from the html has been labeled unobtrusive javascript.

Brandon H
The first concept your refer to is called "Degrading Gracefully"
Jason Punyon
Further, making use of unobtrusive Javascript is generally perceived as the best way to degrade gracefully. Those that view the page without javascript won't get errors, but they won't get the "full" experience as the developer or designer intended. This is why it is important to make your pages functional even if Javascript isn't turned on.
Jared