Skip to content
Advertisement

Can I use ActionCable to refresh the page?

I’ve recently been trying to create a live-scoring system for squash matches. I’ve managed to use ActionCable with Rails 5 to auto-update the score on the page, but I’d like to know if it’s possible to tell Rails to refresh the page if a certain condition is met.

For example, if the game has finished, a different page is shown to say that the players are having a break between games. I need the page to refresh completely for this to happen.

In my database the boolean ‘break’ is marked as true when a game ends, and then the view uses a conditional if/else statement to decide what to show.

The code I use to update the score is attached below, I was thinking something along the lines of if data.break == true then the page will automatically refresh.

// match_channel.js (app/assets/javascripts/channels/match_channel.js)

$(function() {
  $('[data-channel-subscribe="match"]').each(function(index, element) {
    var $element = $(element),
        match_id = $element.data('match-id')
        messageTemplate = $('[data-role="message-template"]');


    App.cable.subscriptions.create(
      {
        channel: "MatchChannel",
        match: match_id
      },
      {
        received: function(data) {
          var content = messageTemplate.children().clone(true, true);
          content.find('[data-role="player_score"]').text(data.player_score);
          content.find('[data-role="opponent_score"]').text(data.opponent_score);
          content.find('[data-role="server_name"]').text(data.server_name);
          content.find('[data-role="side"]').text(data.side);

          $element.append(content);
        }
      }
    );
  });
});

I don’t know if this sort of thing is possible, and I’m not much good at anything Javascript related so I’d appreciate any help on this.

Thanks.

Advertisement

Answer

Reloading the current page is relatively straightforward. If you are using Turbolinks, you can use Turbolinks.visit(location.toString()) to trigger a revisit to the current page. If you aren’t using Turbolinks, use location.reload(). So, your received function might look like:

received: function(data) {
  if (data.break) {
    return location.reload();
    // or...
    // return Turbolinks.visit(location.toString());
  }

  // your DOM updates
}

Either way is the equivalent to the user hitting the reload button, so it will trigger another GET, which calls your controller and re-renders the view.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement