weixin_33738578 2015-08-26 19:26 采纳率: 0%
浏览 19

Rails的事件监听器

I want to try to make a simple real-time chat Rails web app, but I thought I would need some kind of let's call it "event listener" to be able to keep track of sent messages so the receiver user's feed get updated with the new message. Also, for the Typing... notice box.

I hope I explained myself.

I guess I could do it in a very troglodyte way to achieve this like follows:

main.js:

while(true) {
    $.get('/user-you-are-talking-to/are-there-new-messages', function(data) {
        if (data['are_there_new_messages'] === true) {
            $('#conversation').append(data['new_message']);
        }
    });
}

conversation_controller.rb:

# routed by /user-you-are-talking-to/are-there-new-messages'
def new_messages?
    unless @new_messages.blank?
        @json = []
        @json[:are_there_new_messages] = @new_messages.count > 0
        @json[:new_message]= @new_messages.shift
        render json: @json
    end
end

But well aside than the fact that I didn't test that code, a while loop and constant requests to the server seem like a really really bad idea, obviously.

I would like to know if Rails has a built-in feature like this, but as far as I know it doesn't, unlike frameworks I've worked with like Laravel. If there's not a built-in tool for this, how can I do this app?

  • 写回答

2条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 有人用过颜色传感器吗?
      • ¥50 求一个SQL长料切短料的优化排版算法
      • ¥15 python 删除TXT文档中小写字母
      • ¥15 ValueError: not enough values to unpack (expected 2, got 0)
      • ¥15 js怎么禁止修改域名
      • ¥15 Cursor为什么在Windows11打不开
      • ¥30 java调用javacv遇到的问题
      • ¥15 如何使用matlab画出带宽100Khz,时长100ms信号的LFM形式的时频图啊
      • ¥15 Error: [BABEL]: Cannot find module '@vue/babel-preset-app'.报错,求解
      • ¥15 --==关于启动加载mount命令的解决方案==--