Rails 应用程序中的每个 javascript 文件都需要 .on('page:change', initialize) 吗?

Does every single javascript file in a Rails app need .on('page:change', initialize)?

假设我有一个 rails 应用程序 "restful." 假设我有一堆资源:blogbookuser、一个 comment 等等

这些资源中的每一个都有其对应的 javascript 文件:blogs.jsbooks.jsusers.jscomments.js 等。

据我了解,为了与 turbo 链接兼容,这些文件中的每一个都需要具有如下内容:

function initialize(){
    ...
}
$(document).on('page:change', initialize);

据我了解,我必须对每个 js 文件 执行此操作。这是准确的吗?如果它是准确的,有没有办法让我只一次做到这一点,这样所有javascript文件都知道在DOM之前不加载它们的代码(启用 turbo 链接)准备好使用 javascript 代码了吗?它似乎违反了 "Don't repeat yourself" 规则。

或者,如果我认为需要完成的方式不正确,请告诉我我的错误。

As I understand it, I have to do this for every single js file

是的,你是对的,没有最小的解决方法。

但是,您可以使用 jQuery Turbolinks gem :

Gemfile

gem 'jquery-turbolinks'

application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks

...就是这样!

并确保在使用 jQuery Turbolinks不要在您的代码中执行此操作:

/* BAD: don't bind 'document' events while inside $()! */
$(function() {
  $(document).on('click', 'button', function() { ... })
});

而是这个:

/* Good: events are bound outside a $() wrapper. */
$(document).on('click', 'button', function() { ... })