正确的“Rails”方式在特定页面上执行javascript

时间:2015-05-08 22:29:42

标签: javascript jquery ruby-on-rails ruby-on-rails-4

我正在尝试在特定页面上运行javascript,我唯一的解决方案似乎是反模式。我在controller.js内生成assets/javascripts/。我正在使用gem 'jquery-turbolinks'我的代码类似于以下内容:

$(document).ready(function () {
    //Initiate DataTables ect..
    }
)

此代码在每个页面上触发所以我在其中添加了以下内容。

if ($('#page-specific_element').length > 0) {
    //Initiate Datatables ect.
}

我的问题是,有没有办法设置rails只使用特定控制器所需的javascript文件,或者是元素搜索后的逻辑门控搜索最佳解决方案?

1 个答案:

答案 0 :(得分:17)

这是一个非常好的turbolinks特定解决方案:

<body data-controller="<%= controller.controller_name %>" data-action="<%= controller.action_name %>">

// Instead of listening for document ready
$(document).on('users#show:loaded', function(){
    $('#logger').append('<li>Users Show action loaded</li>');
});

// Instead of listening for document ready
$(document).on('users:loaded', function(){
    $('#logger').append('<li>Some users controller method loaded</li>');
});

// Turbolinks fires "page:change" when it changes the page content.
// you could change this to just document ready if you are not using 
// turbolinks.
$(document).on("page:change", function(){
  var data = $('body').data();
  $(document).trigger(data.controller + ':loaded');
  $(document).trigger(data.controller + '#' + data.action + ':loaded');
});

// This is just for demonstration purposes...
$(document).trigger("page:change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body data-controller="users" data-action="show">

  <ul id="logger"></ul>
</body>

您应该注意,如果您正在使用Turbolinks,那么您将拥有一个长期运行的持久会话并保持状态。这意味着如果您在视图中添加内联脚本标记或加载其他javascript文件,它们将在浏览器内存中停留。

因此,您可能希望清理在page:before-unload上创建的任何特定于页面的事件处理程序。

相关问题