【问题标题】:Rails 5 ActionCable App is not definedRails 5 ActionCable App 未定义
【发布时间】:2017-07-01 16:15:20
【问题描述】:

我是 Rails 5 中 ActionCable 的新手。我正在尝试为我的 Rails 应用程序进行聊天。当我尝试通过控制台App.room.speak('Test!') 发送测试消息时,但当我这样做时出现错误。

Uncaught ReferenceError: App is not defined at :1:1

房间.咖啡

App.room = App.cable.subscriptions.create "RoomChannel",
  connected: ->
  # Called when the subscription is ready for use on the server

  disconnected: ->
  # Called when the subscription has been terminated by the server

  received: (data) ->
  # Called when there's incoming data on the websocket for this channel
  $('message').append data

  speak: (message)->
  @perform 'speak', message: message

room_channel.rb

class RoomChannel < ApplicationCable::Channel
   def subscribed
     stream_from "room_channel"
   end

   def unsubscribed
      # Any cleanup needed when channel is unsubscribed
   end

   def speak (data)
     Message.new content: data['message'], user: current_user
   end
end

broadcast_message_job.rb

class BroadcastMessageJobJob < ApplicationJob
   queue_as :default

   def perform(meesage)
     ActionCable.server.broadcast 'room_channel', render_message(message)
   end

   private

   def render_message(message)
     ApplicationController.renderer.render message
   end
end

cable.js

(function() {
   this.App || (this.App = {});

   App.cable = ActionCable.createConsumer();

}).call(this);

routes.rb

mount ActionCable.server => '/cable'

【问题讨论】:

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


    【解决方案1】:

    确保您已在 cable.js 文件中添加了 require_self

    // app/assets/javascripts/cable.js
    //= require action_cable
    //= require_self
    //= require_tree ./channels
    
    (function() {
      this.App || (this.App = {});
      App.cable = ActionCable.createConsumer();
    }).call(this);
    

    这将添加来自同一个cable.js 文件的内容,如果您在其他文件中定义了App,那么您需要在“require”部分中添加它。

    【讨论】:

    • 在定义App 时,js 文件加载顺序是否重要?如果相同的匿名函数在另一个文件中,那么如果它已经被声明或以其他方式将其设置为空对象并开始使用它,那么使用this.App 的结果是否相同?
    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2019-01-08
    • 2016-11-22
    • 2017-03-13
    • 1970-01-01
    相关资源
    最近更新 更多