【发布时间】:2017-12-05 18:32:51
【问题描述】:
有一个链接可以从 current_users 屏幕中删除一条消息:
= link_to '[x]', msg, method: :delete, remote: true, class: "del-link"
它触发了这个咖啡脚本功能:
delete_message = () ->
$('.del-link').on 'ajax:success', (event) ->
event.preventDefault()
$(this).closest('.message').remove()
return
还有这个 rails 方法:
def destroy
@msg = Msg.find(params[:id])
@msg.destroy
respond_to do |format|
format.html { redirect_to chat_path }
format.json { head :no_content }
format.js { render :layout => false }
end
end
但是如何做到,在每个用户屏幕上删除消息,例如使用 ActionCable?
聊天的咖啡脚本:
App.proom = App.cable.subscriptions.create "ProomChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
unless data.msg.blank?
$('#messages-table').append data.msg
scroll_bottom()
$(document).on "turbolinks:load", ->
submit_msg()
scroll_bottom()
delete_message()
频道.rb
class ProomChannel < ApplicationCable::Channel
def subscribed
stream_from "proom_channel"
end
def unsubscribed
end
end
方法
所以我将它添加到控制器的销毁操作中
if msg.destroy
ActionCable.server.broadcast 'proom_channel', msg: @msg
end
我还为每个包含消息记录 id 的 message-div-element 添加了一个 ID,以便使用以下行从 DOM 中查找和删除它
$("msg_#{msg.id}").remove()
但现在我不知道该放在哪里。
【问题讨论】:
标签: javascript ruby-on-rails coffeescript actioncable