public Method

JavaScriptHelper.link_to_function(name, *args, &block)

Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.

The function argument can be omitted in favor of an update_page block, which evaluates to a string when the template is rendered (instead of making an Ajax request first).

Examples:

link_to_function "Greeting", "alert('Hello world!')"
  Produces:
    <a href="#" onclick="alert('Hello world!'); return false;">Greeting</a>

link_to_function(image_tag("delete"), "if (confirm('Really?')) do_delete()")
  Produces:
    <a href="#" onclick="if (confirm('Really?')) do_delete(); return false;">
      <img src="/images/delete.png?" alt="Delete" />
    </a>

link_to_function("Show me more", nil, :id => "more_link") do |page|
  page[:details].visual_effect  :toggle_blind
  page[:more_link].replace_html "Show me less"
end
  Produces:
    <a href="#" onclick="try {
      $(&quot;details&quot;).visualEffect(&quot;toggle_blind&quot;);
      $(&quot;more_link&quot;).update(&quot;Show me less&quot;);
    }
    catch (e) {
      alert('RJS error:\n\n' + e.toString());
      alert('$(\&quot;details\&quot;).visualEffect(\&quot;toggle_blind\&quot;);
      \n$(\&quot;more_link\&quot;).update(\&quot;Show me less\&quot;);');
      throw e
    };
    return false;">Show me more</a>

Source Code

# File action_view/helpers/javascript_helper.rb, line 82
def link_to_function(name, *args, &block)
  html_options = args.extract_options!
  function = args[0] || ''

  html_options.symbolize_keys!
  function = update_page(&block) if block_given?
  content_tag(
    "a", name, 
    html_options.merge({ 
      :href => html_options[:href] || "#", 
      :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function}; return false;" 
    })
  )
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.