A neat little trick is that .rjs templates can be used to generate local javascript functions and be invoked without doing a server roundtrip.
playground_controller.rb
class PlaygroundController < ApplicationController
def rjs
response.headers[‘content-type’] = ‘text/html’
end
end
rjs.rhtml
<%= javascript_include_tag :defaults %>
<%= link_to_function(‘Add’, ‘add_item()’ ) -%> |
<%= link_to_function(‘Clear’, ‘clear_list()’) >
The rjs method in the PlaygroundController set’s the content-type as we perform a render of an rjs from within a .rhtml and this seems to change the content-type, so we need to reset it.
_function.rjs
page << ‘function add_item() {’
page.insert_html :bottom, ‘list’, content_tag(‘li’, ‘item’, :id => ‘list_item’ )
page.visual_effect :highlight, ‘list’, :duration => 3
page << ‘}’
page << ‘function clear_list() {’
page.replace_html :list, ""
page.visual_effect :highlight, ‘list’, :duration => 3
page << ‘}’
In the partial function.rjs we insert the function declaration before writing to the page object. This allows us to invoke the additem _ and clear_list _ methods using the link_to_function _ from in the .rhtml file. Note also in the .rhtml file we invoke directly the update_page method to insert three calls to add_item().
The generated html files looks like this