正确的“路轨"在特定页面上执行javascript的方法 [英] Proper "Rails" way to perform javascript on specific pages
问题描述
我正在尝试在特定页面上运行javascript,而我唯一的解决方案似乎是一种反模式.我在assets/javascripts/
内部生成了controller.js
.我正在使用gem 'jquery-turbolinks'
,我的代码类似于以下内容:
I'm attempting to run javascript on specific pages and my only solution seems like an anti-pattern. I have controller.js
generated inside of assets/javascripts/
. I'm using gem 'jquery-turbolinks'
I have code resembling the following:
$(document).ready(function () {
//Initiate DataTables ect..
}
)
此代码在每个页面上触发,因此我在其中添加了以下内容.
This code is firing on every page So I added the following inside of it.
if ($('#page-specific_element').length > 0) {
//Initiate Datatables ect.
}
我的问题是,有没有一种方法可以设置导轨以仅利用特定控制器所需的javascript文件,或者逻辑门控在元素搜索之后是最佳解决方案?
My question being, is there a way to set rails to utilize only the javascript files necessary to a specific controller or is logic gating behind an element search the best solution?
推荐答案
这是一个非常不错的Turbolink特定解决方案:
This is a pretty nice turbolinks specific solution:
<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文件,它们将在浏览器内存中徘徊.
You should note that if you are using Turbolinks that you'll have a long-running, persistent session with maintained state. Which means that if you add inline script tags or load additional javascript files in your views they will linger in the browsers memory.
因此,您可能想要清除在page:before-unload
上创建的所有页面特定的事件处理程序.
You therefore might therefore want to cleanup whatever page specific event handlers you have created on page:before-unload
.
这篇关于正确的“路轨"在特定页面上执行javascript的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!