Raju akula
Raju akula

Reputation: 1305

What is Unobtrusive JavaScript in rails?

I would like to use Ujs in my rails 3 app. Can any one explain me about obtrusive and unobtrusive javascripts in rails? why does rails 3 before versions don't support ujs ?

Upvotes: 2

Views: 532

Answers (1)

Agush
Agush

Reputation: 5116

Rails has had javascript helpers since early versions.

The difference since Rails 3 is that now it's unobtrusive, by unobtrusive it means that functionality its separated from content.

For example the following:

<%= link_to "Delete", resource_path(@resource), :method => "delete", :confirm => "Are you sure?" %>

Would render pre Rails 3

<a href="/resource/1" onclick="//lots and lots of inline javascript code here">Delete</a>

With Rails 3 UJS

<a href="/resource/1" data-method="delete" data-confirm="Are you sure?">Delete</a>

The difference is that unobtrusive javascript is handled without inline code in the views and passed through the "data" attributes and taken care of in the background with other default JS that is in your app that picks up this data attributes and runs the corresponding JS code.

UJS is also commonly used for making remote (AJAX) calls using :remote => "true" or link_to_remote.

More info on that here: AJAX on Rails


Basically UJS means that the javascript helpers included in Rails such as confirmation, and AJAX, among others are separated from the view code (HTML).

UJS helpers can also be easily switched out for example if you prefer to use Prototype you could switch easily from jQuery while keeping the helpers functionality.

Why Rails older versions didn't support UJS, is because it just wasn't built in at the time, so it was done with inline JS.

Upvotes: 4

Related Questions