Drag and Drop with script.aculo.us and Rails
(Page 1 of 4 )
In this second part to a three-part series that explains how to use script.aculo.us on Rails, you'll learn how to use a Rails helper and drag and drop. This article is excerpted from chapter four of
Ajax on Rails, written by Scott Raymond (O'Reilly, 2007; ISBN: 0596527446). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Visual Effect Helper
So far, we’ve been using script.aculo.us’s Effect object directly, without the aid of Rails helpers. Rails also provides a helper to generate visual effects, allowing you to create effects without writing JavaScript. The helper isvisual_effect, and it’s used like this:
visual_effect(:fade, :target)
The first argument is the name of a script.aculo.us effect (almost—see the note below), and the second is the ID of a DOM element. Thevisual_effecthelper outputs a JavaScript snippet, so it’s usually used in combination with another helper, likelink_to_function:
<li><%= link_to_function "Fade", visual_effect(:fade, :target) %></li>
The toggle effects can be used from the helper method as well:
<%= link_to_function "Toggle Blind",
visual_effect(:toggle_blind, :target) %>
Standard Ruby style is to use underscores to separate words in variable and method names. The script.aculo.us effect methods, on the other hand, follow the JavaScript convention of “CamelCase.” So when you are using thevisual_effecthelper, remember to use the lower-case, underscored versions of the effect names; e.g.,BlindUp becomesblind_up.
Thevisual_effecthelper is especially useful when combined with Ajax helpers, such aslink_to_remote. For example, you might use theHighlighteffect to draw the user’s attention to a portion of the page that has been updated via Ajax. To see it in action, first add a new action to chapter4_controller.rb:
def get_time
render :text => Time.now
end
And then create an Ajax link to it in views/chapter4/ index.rhtml:
<%= link_to_remote "Get Time",
:update => "current_time",
:url => { :controller => "chapter3", :action => "get_time" },
:complete => visual_effect(:highlight, :current_time) %>
<div id="current_time"></div>
Notice that, unlike the examples in the last chapter, we aren’t writing custom JavaScript in the:completeoption—instead, we let thevisual_effecthelper write it for us.
Next: Drag and Drop >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Ajax on Rails, written by Scott Raymond (O'Reilly, 2007; ISBN: 0596527446). Check it out today at your favorite bookstore. Buy this book now.
|
|