How do I call a JavaScript function from an erb te

2019-07-15 07:54发布

If you define a JavaScript function and then call it from an erb template the function does not get called. Why? Clicking this link should show an alert, but it does not.

= link_to "Add Sprout", new_sprout_path, remote: true

Controller:

def new
  @sprout = Sprout.new
  respond_to { |format| format.js }
end

Then in the template I call a function:

# sprouts/new.js.erb
doSomething();

The function is defined in my js files:

# javascripts/sprouts.js.coffee
doSomething = ->
  alert "yum ghum I am a new sprout."

The JavaScript comes back. I can see it in the console. But I see no alert. Why doesn't this not work?

I'm using Rails 4.

1条回答
Rolldiameter
2楼-- · 2019-07-15 08:32
@doSomething = -> alert "yum ghum I am a new sprout."

or

window.doSomething = -> alert "yum ghum I am a new sprout." # I prefer this approach, as it's more explicit.
查看更多
登录 后发表回答