Question

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.

Was it helpful?

Solution 2

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'));
  });
});

OTHER TIPS

In cases like this, pass the needed info as data to html elements and move the javascript to an asset file.

html

<div id='customer-info' data-channel='<%= @customer.channel %>' data-customer-id='<% @customer.id %>'</div>

JS (coffee)

if $('#customer-info').length
  pubnub.subscribe
    channel: $('#customer-info').data('channel')
    message: (message) ->
    if message.customer_id == $('#customer-info').data('customer-id')
      alert('same user')

And since you're using turbolinks, make sure that the code runs when the page is loaded via turbolinks. The easiest way to make sure of this is to use the jquery-turbolinks gem

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top