我在使用动作电缆时遇到了麻烦,我在前端使用了JavaScript的Rails应用程序,我的前端连接到了动作电缆,但是方法received
从未调用,而connected
是调用,我从ActionCable接收ping
。
这是我的JavaScript代码:
categories.js
$(document).ready(function () {
App.category = App.cable.subscriptions.create("CategoryChannel",
{
received: function(data) {
console.log(data);
alert("Category is done!");
},
disconnected: function() {
console.log("We are not connected");
},
connected: function () {
console.log("We are connected");
}
}
);
});
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);
这是我的频道:
category_channel.rb
class CategoryChannel < ApplicationCable::Channel
def subscribed
# stream_from "some_channel"
stream_for 'categories'
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
我的红宝石代码:
categories_controller.rb
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
ActionCable.server.broadcast 'categories', { category: @category }
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: @category }
else
format.html { render :new }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
我的电缆。yml
development:
adapter: redis
url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
您有帮助我的想法吗?
今天愉快。