This is my sixth month using Rails. It was difficult letting go of the tendency to hand-code the JavaScript. I had used Prototype and Scriptaculous at OCP, so hand-coding was a no-brainer. At first glance the Rails/Javascript integration didn't look like it would do much for what I needed. Looks were deceptive, though.
The integration features has its strengths and weaknesses. It's good at sprinkling dynamic behavior on HTML elements. Here's an example (formatted for readability):
<%= link_to 'Hide Comments', '#',
:id => 'hide_comments_link',
:style => 'display:none',
:onclick => visual_effect(
:blind_up,
'comments',
:after_finish => "function() { $('comments').update(); }"
) +
"$('hide_comments_link').hide();" +
"$('show_comments_link').show();" +
" return false;"
%>
Here's how it renders (again, highly formatted for readability):<a href="#"
id="hide_comments_link"
onclick="
new Effect.BlindUp("comments",{
after_finish: function() {
$('comments').update();
}
});
$('hide_comments_link').hide();
$('show_comments_link').show();
return false;
"
style="display:none"
>Hide Comments</a>
The big advantage here is that the underlying JavaScript libraries, Prototype and Scriptaculous, can change their API over time, and Rails will adjust, saving the programmer from having to update code to the new APIs.There are more advantages:
- The developer can stick with the Ruby and ROR coding conventions and syntax. No need to switch from underscore naming to camel case. No need to switch to the quirky JavaScript syntax (e.g.,
new Effect.BlindUp('comments')becomesvisual_effect(:blind_up, 'comments') - The syntax for adding the JavaScript code is the same syntax already used for creating HTML elements with Rails' helper methods.
- No need to worry about escaping characters that could be mis-interpreted as HTML syntax characters (<, >, "). This is doubly helpful when an attribute such as
onclick-""contains JavaScript with double-quoted strings (see generated HTML above).
0 comments:
Post a Comment