【问题标题】:Uncaught TypeError: this.perform is not a function in rails 6未捕获的 TypeError:this.perform 不是 rails 6 中的函数
【发布时间】:2019-11-11 12:46:29
【问题描述】:

我开始使用 Rails 6 中的 ActionCable,它运行良好,但是 我不知道为什么 poke_channel.js 中未定义“.perform”方法。 请问我需要你的帮助

# in app/channels/poke_channel.rb

class PokeChannel < ApplicationCable::Channel
  def subscribed
    stream_from "poke"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def poke(data)
    ActionCable.server.broadcast('poke')
  end
end

# in app/javascript/channels/poke_channels.js
import consumer from "./consumer"

consumer.subscriptions.create("PokeChannel", {
  connected() { 
    $('#poke-btn').click(function(event) {
      this.perform("poke", {});
    });
    // Called when the subscription is ready for use on the server
  },

  disconnected() {
    // Called when the subscription has been terminated by the server
  },

  received(data) {
    alert('Poked');
    // Called when there's incoming data on the websocket for this channel
  },

});

# in app/views/messages/index.html.erb

<button id="poke-btn">Poke</button>

当我点击按钮时,

poke_channel.js:6 Uncaught TypeError: this.perform is not a function
at HTMLButtonElement.<anonymous> (poke_channel.js:6)
at HTMLButtonElement.dispatch (event.js:328)
at HTMLButtonElement.elemData.handle (event.js:148)

【问题讨论】:

    标签: actioncable ruby-on-rails-6


    【解决方案1】:

    我遇到了这个问题,以下对我有用。

    尝试获取您创建的订阅并将其保存到某处,然后对其调用执行。

    this.channel = consumer.subscriptions.create("PokeChannel", {
      connected() { 
        $('#poke-btn').click(function(event) {
          this.channel.perform("poke", {});
        });
        // Called when the subscription is ready for use on the server
      },
      ...
    });

    【讨论】:

      最近更新 更多