Question

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.

Was it helpful?

Solution

@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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top