我从rails 6中的ActionCable开始,它运行得很好,但我不知道为什么poke_channel.js中没有定义".sperform"方法。我需要你的帮助
# 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)
我遇到了这个问题,下面的问题对我有效。
尝试将创建的订阅保存到某个位置,然后调用perform。
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
},
...
});