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.

    评论

报告相同问题?