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条回答 默认 最新

  • weixin_33691598 2015-08-26 19:29
    关注

    Real time apps are usually done with websockets.

    https://github.com/eventmachine/eventmachine

    https://github.com/igrigorik/em-websocket

    Or if on a hosted service you can use a publish/subscribe service such as Pusher or PubNub.

    Otherwise, you would do polling which is what you have in your example.

    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿