未捕获的TypeError:this.perform不是Rails 6中的函数

时间:2019-11-11 12:46:29

标签: actioncable ruby-on-rails-6

我将在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)

1 个答案:

答案 0 :(得分:0)

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

尝试获取已创建的订阅,然后将其保存到某项中,然后在其上调用执行。

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
  },
  ...
});