Search code examples
javascriptruby-on-railsturbolinks

how to reload ruby inserted into javascript - turbolinks


I have a rails 4 app with turbolinks. I insert ruby variables into my javascript however when I click a link, the variables don't get reset since the javascript isn't being reset. How do I make sure the each time a user goes to another page, it reloads the ruby inserted into the javascript?

EDIT MORE INFO:

pubnub.subscribe({
      channel : "#{@customer.channel}",
      message : function(message){
        if(message.customer_id == #{@customer.id}){
          debugger;
          $('#message').append($('<li>').text("#{@customer.first_name}" + ': (' + "#{Time.now.utc.to_s(:time)}" + ') '+ message.text));
        }
      }
    });

basically, if I'm looking at @customer.id's page, it works...then when I click to antoher page, @customer.id is the same as the previous page.


Solution

  • The best approach is to never put Ruby variables into your JavaScript.

    I prefer to use data attributes in the DOM to pass values from the server to the client code:

    <div class='my-pubnub-widget' data-pubnub-opts= '<%= @ruby_hash.to_json %>'></div>
    

    And in JavaScript

    function setupPubnub(opts) {
      pubnub.subscribe({
        channel : opts.channel,
        message : function(message){
          if(message.customer_id == opts.id){
            $('#message').append($('<li>').text(opts.first_name + ': (' + opts.time + ') '+ message.text));
          }
        }
      });
    }
    
    $(document).on('page:load', function () { // turbolinks ready event
      $('.my-pubnub-widget').each(function () {
        setupPubnum($(this).data('pubnub-opts'));
      });
    });