Question

It seems like it'd be possible to use turbolinks to automatically refresh the body of the page, but I haven't been able to find anything about how to do this. Is it possible? If so, could you point me to a resource on how to do it?

I'm not looking for how to refresh the whole page - that seems quite heavy. I'm also not asking about polling for changes, or using something like Faye to keep the page in sync. While any of these methods would work, I'm specifically asking if this is possible with turbolinks since I'm new to this feature and learning what it can do.

Était-ce utile?

La solution

I thought about it some more, and realised I could have a very simple solution:

A hidden link to the current page

link_to 'current page', params, id: 'refresh_page_link', style: 'display:none;'

A tiny bit of coffeescript to trigger a click on that link every 5 seconds.

reload_periodically = ->

  setTimeout (->
    $('#refresh_page_link')[0].click();
    return
  ), 5000 # 5 seconds

$(document).ready(reload_periodically)
$(document).on('page:load', reload_periodically)

That results in a weird flash on the page every reload. Clearly there are better ways to do this that wouldn't have the flash. I just wanted to learn more about turbolinks.

Autres conseils

I think you're asking the wrong question

Turbolinks is meant for when you're switching between views -- it helps limit the number of requests made to the server:

Turbolinks makes following links in your web application faster. Instead of letting the browser recompile the JavaScript and CSS between each page change, it keeps the current page instance alive and replaces only the body and the title in the head


Polling

What you're really looking for is "live" functionality:

  • Ajax Polling (typically with SSE's)
  • WebSockets

Rails runs on the HTTP structure, meaning you send a request, it replies. The problem is this prohibits Rails from generating a request from server side. Technology such as ActionController::Live has been created to remedy this, but it's sketchy

I'd recommend using a service called Pusher

This is pub/sub tech, works by giving you an eventListener in your JS, basically "listening" to any updates from your server. You can then publish the updates through Rails' Pusher gem:

    #app/assets/javascripts/application.js.coffee
    pusher = new Pusher("*************", cluster: 'eu')

    channel = pusher.subscribe("private-user-#{gon.user}")
    channel.bind "multi_destroy", (data) ->
    # do your stuff here

    #app/controllers/message.rb
    def send_message
        public_key = self.user.public_key
        Pusher['private-user-' + public_key].trigger('message_sent', {
            message: "Message Sent"
        })  
    end
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top