How do I call a JavaScript function from an erb template?

雨燕双飞 提交于 2019-12-11 01:48: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:


@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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!