简体   繁体   中英

Correct way to use coffee script in rails5

I am developing my first rails application and trying to show/hide a particular web element in my view by clicking an another link in my page. Below is my view,

%p
 = link_to 'Show additional details', "#", id: "secondary-link"

%table{:id => "secondary"}
 %tr
  %th Key
  %th Value

where "secondary-link" is the link which shows / hides my table. When the page is loaded first, the table is made to hide by the following line in my application.css.scss

#secondary{
 display: none;
}

Also, i have added this following script in my assets/javascripts/application.coffee

@myFunction = (variable) ->
  $(document).on "page:change", ->
    $('#secondary-link').click ->
      $('#secondary').toggle()

But, the table is not shown when i click the link in my page. However, in my console if i enter "myFunction" i am getting the function

ƒ (variable) {
 return $(document).on("page:change", function() {
   return $('#secondary-link').click(function() {
     return $('#secondary').toggle();
   });
 });
}

and i am getting an error when i enter myFunction()

Uncaught TypeError: Cannot read property 'on' of undefined
at myFunction (application.self-4e74630fd8894bca1e22a8d66c1d7ebfaa39edf4f40e058aae03fc788a9f6d94.js?body=1:3)
at <anonymous>:1:1

Your help is appreciated.

I am not sure why this issue but i fixed it by using jquery directly in my application.js file and deleted the coffee file. My js file has the below coding to handle the event.

$(document).ready(function() {
  $('#secondary-link').click(function(event){
     return $('#secondary').toggle();
  });
});

I have stopped and restarted the server and this worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM