Lee Tang
Lee Tang

Reputation:

Why do the Rails helper methods prevent "unobtrusive JavaScript"?

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

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

Upvotes: 2

Views: 755

Answers (2)

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.

Upvotes: 3

Brandon Henry
Brandon Henry

Reputation: 3719

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.

Upvotes: 0

Related Questions