【问题标题】:Setting up Rails5 Action Cable设置 Rails5 动作电缆
【发布时间】:2016-02-12 15:24:16
【问题描述】:

我正在关注 DHH 的教程。一切顺利,直到我将此代码添加到 room.coffee

$(document).on 'keypress', '[data-behavior~=room_speaker]', (event) ->
  if event.keyCode is 13 # return = send
  App.room.speak event.target.value
  event.target.value = ''
  event.preventDefault()

只要我这样做,我就会得到:

SyntaxError: [stdin]:15:3: unexpected if

提取的源代码(第 8 行附近):

6    <%= action_cable_meta_tag %>
7
8    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
9    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  </head>

我正在使用 Rails 5.0.0.beta2、Ruby 2.3.0,并在 OS X 10.11.3 上运行

奇怪的是,当我在 room.coffee 上更改某些内容(代码似乎正确?)时,错误似乎出现在 application.html.erb

帮助表示赞赏!

【问题讨论】:

    标签: ruby-on-rails coffeescript ruby-on-rails-5


    【解决方案1】:

    Javascript 错误与 Action Cable 无关。你得到它是因为你的 if 没有正文。

    你的代码,因为它目前是缩进的,翻译成没有意义的东西,因此错误

    $(document).on('keypress', '[data-behavior~=room_speaker]', function(event) {
        if (event.keyCode === 13)
        App.room.speak(event.target.value);
        event.target.value = '';        
        return event.preventDefault();
    });
    

    这就是你想要的。注意缩进。

    $(document).on 'keypress', '[data-behavior~=room_speaker]', (event) ->
      if event.keyCode is 13 # return = send
        App.room.speak event.target.value
        event.target.value = ''
        event.preventDefault()
    

    翻译成

    $(document).on('keypress', '[data-behavior~=room_speaker]', function(event) {
        if (event.keyCode === 13) {
            App.room.speak(event.target.value);
            event.target.value = '';        
            return event.preventDefault();
        }
    });
    

    【讨论】:

    • 尴尬——我的错。这么容易就整理好了。非常感谢您的快速回答。
    猜你喜欢
    • 2016-11-23
    • 2018-07-29
    • 2016-08-04
    • 1970-01-01
    • 2017-01-27
    • 2018-04-20
    • 2017-05-27
    • 2021-01-28
    相关资源
    最近更新 更多