如何将ruby重新加载到javascript-turbolinks中

如何将ruby重新加载到javascript-turbolinks中,javascript,ruby-on-rails,turbolinks,Javascript,Ruby On Rails,Turbolinks,我有一个带有TurboLink的rails 4应用程序。我在javascript中插入ruby变量,但是当我单击链接时,这些变量不会被重置,因为javascript没有被重置。我如何确保用户每次转到另一个页面时,都会重新加载插入到javascript中的ruby 编辑更多信息: pubnub.subscribe({ channel : "#{@customer.channel}", message : function(message){ if(messa

我有一个带有TurboLink的rails 4应用程序。我在javascript中插入ruby变量,但是当我单击链接时,这些变量不会被重置,因为javascript没有被重置。我如何确保用户每次转到另一个页面时,都会重新加载插入到javascript中的ruby

编辑更多信息:

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));
        }
      }
    });
publinub.subscribe({
频道:“{@customer.channel}”,
消息:函数(消息){
if(message.customer_id=={@customer.id}){
调试器;
$(“#message”).append($(“
  • ”).text(“#{@customer.first#name}”+”:(“+”{Time.now.utc.to#s(:Time)}”+”+message.text)); } } });

  • 基本上,如果我正在查看@customer.id的页面,它会工作……然后当我单击另一个页面时,@customer.id与上一个页面相同。

    在这种情况下,将所需信息作为数据传递给html元素,并将javascript移动到资产文件中

    html

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

    由于您使用的是turbolinks,请确保在通过turbolinks加载页面时代码运行。确保这一点的最简单方法是使用

    最好的方法是永远不要将Ruby变量放入JavaScript中

    我更喜欢使用DOM中的数据属性将值从服务器传递到客户端代码:

    <div class='my-pubnub-widget' data-pubnub-opts= '<%= @ruby_hash.to_json %>'></div>
    
    
    
    和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'));
      });
    });
    
    函数设置PubNub(选项){
    订阅({
    频道:opts.channel,
    消息:函数(消息){
    if(message.customer_id==opts.id){
    $(“#message”).append($(“
  • ”).text(opts.first_name+”:(“+opts.time+”)+message.text)); } } }); } $(document).on('page:load',函数(){//turbolinks ready事件 $('.my pubnub widget')。每个(函数(){ setupPubnum($(this).data('pubnub-opts'); }); });
  • 您刚刚解决了一个我几天来一直试图解决的问题……谢谢您,先生!!
    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'));
      });
    });