简体   繁体   中英

How to refactor link_to_function using unobustrive JS in helper?

I am using link_to_function in one of my ApplicationHelper method:

def link_to_add_fields(name, f, association)
  new_object = f.object.class.reflect_on_association(association).klass.new
  fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
    render(association.to_s + "_fields", :f => builder)
  end
  link_to_function(name, ("add_fields(this, '#{association}', '#{escape_javascript(fields)}')").html_safe)
end

Since it will be deprecated in Rails 4 I would like to get rid of link_to_function using Unobustrive JS. How to do that?

I know this is an old question but I was amused to run across this question with the exact same code snippet as I have... bless you Ryan Bates and RailsCasts!

In any case, this turns out to be a pretty easy refactor. You just have to pass the function as the 'onclick' parameter of link_to:

link_to(name, '#', onclick: "add_fields(this, '#{association}', '#{escape_javascript(fields)}')")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM