简体   繁体   English

在Rails5中使用咖啡脚本的正确方法

[英]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. 我正在开发我的第一个Rails应用程序,并尝试通过单击页面中的另一个链接来显示/隐藏视图中的特定Web元素。 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 第一次加载页面时,该表将由我的application.css.scss中的以下行隐藏

#secondary{
 display: none;
}

Also, i have added this following script in my assets/javascripts/application.coffee 另外,我在我的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 但是,在控制台中,如果我输入“ myFunction”,我将获得该功能

ƒ (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() 当我输入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. 我不确定为什么会出现此问题,但我直接在application.js文件中使用jquery修复了该问题,并删除了coffee文件。 My js file has the below coding to handle the event. 我的js文件具有以下代码来处理事件。

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

I have stopped and restarted the server and this worked. 我已经停止并重新启动服务器,并且此方法有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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