views:

2789

answers:

2

I was just playing around with Rails 3 beta and noticed that link_to_function is now gone. I presume there's an alternate method of achieving the same result (onclick event?) but I was wondering if there's a more Rails-3'y way of doing it. TIA.

+13  A: 

Rails 3 seems to have done away with Prototype Helper in favour of a less obtrusive/JS library agnostic approach. The goal is to eliminate all inline javascript generated by Rails. Prototype Helper generated pretty much all of the javascript.

Now any of the non remote variants of helpers will generate the proper javascript for a remote call in your JS library of choice just by supplying the :remote => true option.

Unfortunately this doesn't hold true for the x to function methods. For the time being there are the prototype legacy helpers which are no longer a core part of Rails.

You could also use call as defined in ActionView::Helpers::PrototypeHelper::JavascriptGenerator::GeneratorMethods to supply javascript code to :onclick as an html_option for link_to, but that's not exactly pretty.

Examples:

Rails < 3                      | Rails 3
link_to_remote "target", url   | link_to "target", url, :remote => true
form_remote_for @post          | form_for @post, :remote => true

etc....

Or something to that effect. I'm having trouble finding official documentation to back up my claims. So the release notes will have to do for now.

Before you can use it, you'll need to include the proper js source files. Ensure that you are loading prototype.js and rails.js, or the library and driver for JS framework of choice in their place.

Remember, Rails 3 is in beta now. But that doesn't mean it's done. I honestly have no idea how link_to_function will be replaced. It goes against the ideal of unobtrusive javascript.

EmFi
The question was about link_to_function (ie. call javascript directly and without the UJS stuff). Thanks for the info anyway.
Psynix
I missed the "function" when I wrote that. I've updated the solution with a better answer to the specific question.
EmFi
A: 

To answer my own question, seems this works and is sufficient for what I need:

link_to "name", nil, :onlick => "alert('Hello, world!')"
Psynix
the problem with that solution is that is totally obtrusive. I would recomend you to play with jquery or prototype + low pro.
VP
I don't think this is "totally" obtrusive, as long as you just call a handler from onclick="" instead of implementing it right there. The whole UJS stuff is not mature yet and even its creators do not agree on what is recommended (see http://weblog.jamisbuck.org/2010/3/2/unobtrusive-yet-explicit including comments).
Matt