Move before-cache event calls to application.js

Turbolinks 5 handles page caching differently; it saves the current HTML
and, when the page is restored using the browser's back button, it
copies it and triggers the `turbolinks:load` event, which, in our case,
triggers our `initialize_modules` function.

This isn't a problem regarding event handlers, since they're removed
when caching the page (except fot the ones attached to the `document`).
However, it is a problem for functions that, once the document is ready,
scan the DOM and add certain elements. In this case, an element might be
added a second time when the page is restored.

So we need to either check an item has already been added before adding
it or remove it before caching the page. Since this is going to be a
common pattern, we're adding a function to handle these non-idempotent
parts of the application, so it mirrors our `initialize_modules`
function.

We're also moving the `destroy` function definition after the
`initialize` function definition, which makes more sense since we
initialize things before destroying them.
This commit is contained in:
Javi Martín
2020-08-03 14:08:26 +02:00
parent 0270c4c962
commit 6bb9ebf12f
2 changed files with 12 additions and 7 deletions

View File

@@ -1,11 +1,6 @@
(function() {
"use strict";
App.HTMLEditor = {
destroy: function() {
for (var name in CKEDITOR.instances) {
CKEDITOR.instances[name].destroy();
}
},
initialize: function() {
$("textarea.html-area").each(function() {
if ($(this).hasClass("admin")) {
@@ -14,8 +9,11 @@
CKEDITOR.replace(this.name, { language: $("html").attr("lang") });
}
});
},
destroy: function() {
for (var name in CKEDITOR.instances) {
CKEDITOR.instances[name].destroy();
}
}
};
$(document).on("turbolinks:before-cache", App.HTMLEditor.destroy);
}).call(this);