CoffeeScript working strangely with Rails 4 -


i cannot coffeescript working rails. first time i'm using coffeescript , i'm new rails too, don't know how make simple coffeescript function work in right way. below people.js.coffee file @ app/assets/javascript directory.

myfunction = -> alert "test" 

the alert “test” message only shows when load page (app/views/people.html.erb , _form.html.erb partial); not when click below button in form:

<%= submit_tag "test coffeescript", :type => 'button',  :id => 'coffeescript', :onclick => 'myfunction()' %>  

i don't know why strange behaviour happening. why :onclick not working? generated source code button should ok:

  <input id="coffeescript" name="commit" onclick="myfunction()"  type="button" value="test coffeescript" />  

below application.js file @ app/assets/javascript.

... // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . 

my ruby version 2.1.0 here values when ran bundle show command:

  • coffee-rails (4.0.1)
  • coffee-script (2.2.0)
  • coffee-script-source (1.7.0)
  • jbuilder (1.5.3)
  • jquery-rails (3.1.0)
  • rails (4.0.2)
  • railties (4.0.2)
  • sass (3.2.19)
  • sass-rails (4.0.3)
  • sprockets (2.11.0)
  • sprockets-rails (2.0.1)
  • turbolinks (2.2.2)

my javascript files working ok; tried similar type of function in javascript , ok.

it's because function in scope. can either unobtrusive jquery.

$ ->   myfunction = ->     alert("test")    $("#coffeescript").on "click", ->     myfunction() 

and remove onclick handler

<%= submit_tag "test coffeescript", type: 'button', id: 'coffeescript' %>  

or...

root = exports ? root.myfunction = () -> alert("test!") 

i'd recommend first one, opinion though. also, have careful indentation in coffeescript, works lot python, whitespace matters.

an explanation on scopes , js/coffee here how define global variables in coffeescript?


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -