From 6bb9ebf12ff1e414462b3ca54f23f71cd0ed4ac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Mon, 3 Aug 2020 14:08:26 +0200 Subject: [PATCH] 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. --- app/assets/javascripts/application.js | 7 +++++++ app/assets/javascripts/html_editor.js | 12 +++++------- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js index 9c1a7d602..776f9931e 100644 --- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -166,4 +166,11 @@ var initialize_modules = function() { App.BudgetEditAssociations.initialize(); }; +var destroy_non_idempotent_modules = function() { + "use strict"; + + App.HTMLEditor.destroy(); +}; + $(document).on("turbolinks:load", initialize_modules); +$(document).on("turbolinks:before-cache", destroy_non_idempotent_modules); diff --git a/app/assets/javascripts/html_editor.js b/app/assets/javascripts/html_editor.js index affdc7034..e1602509d 100644 --- a/app/assets/javascripts/html_editor.js +++ b/app/assets/javascripts/html_editor.js @@ -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);