一段时间后,我将重新学习ActionCable,并且在一个细节上有些卡住。在日志中,我确实看到:
[ActionCable] Broadcasting to some_channel: "new value"
但是当我广播时,不会调用js中收到的函数。
到目前为止,这是我的代码:
# value_update_channel.rb
class ValueUpdateChannel < ApplicationCable::Channel
def subscribed
# stream_from "some_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def method1
end
def method2
end
end
# value_update.js
App.value_update = App.cable.subscriptions.create("ValueUpdateChannel", {
connected: function() {
// Called when the subscription is ready for use on the server
console.log("value_update.js subscribed")
},
disconnected: function() {
console.log("value_update.js disconnected")
// Called when the subscription has been terminated by the server
},
received: function(data) {
console.log("value_update.js data")
// Called when there's incoming data on the websocket for this channel
},
method1: function() {
return this.perform('method1');
},
method2: function() {
return this.perform('method2');
}
});
# cable.js
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels
(function() {
this.App || (this.App = {});
App.cable = ActionCable.createConsumer();
}).call(this);
# update action in values_controller.rb
def update
respond_to do |format|
if @value.update(value_params)
format.html { redirect_to @value, notice: 'Value was successfully updated.' }
format.json { render :show, status: :ok, location: @value }
ActionCable.server.broadcast 'some_channel', "new value"
else
format.html { render :edit }
format.json { render json: @value.errors, status: :unprocessable_entity }
end
end
end