问题
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:
@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.
来源:https://stackoverflow.com/questions/18595739/how-do-i-call-a-javascript-function-from-an-erb-template