From 467be3a3394f7e46e6740c2fbb7061c7abeddc17 Mon Sep 17 00:00:00 2001 From: Tom Byers Date: Tue, 15 Feb 2022 11:05:28 +0000 Subject: [PATCH] Fixes for updateContent based on PR comments Includes the following: Guard for adding duplicate classNames Stops the code that allows classNames to persist across updates to the component HTML from adding a className multiple times to the list of those to persist. From this comment on the associated pull request: https://github.com/alphagov/notifications-admin/pull/4155#discussion_r804639058 Add comment explaining guard for operations on elements no longer in the DOM The value of this guard can be unclear and why it is needed so we add a comment to explain this. From this comment on the associated pull request: https://github.com/alphagov/notifications-admin/pull/4155#discussion_r804697189 --- app/assets/javascripts/updateContent.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/assets/javascripts/updateContent.js b/app/assets/javascripts/updateContent.js index 1dee22e37..c21287bfc 100644 --- a/app/assets/javascripts/updateContent.js +++ b/app/assets/javascripts/updateContent.js @@ -17,7 +17,9 @@ _classNames: [], _$els: [], addClassName: function (className) { - this._classNames.push(className); + if (this._classNames.indexOf(className) === -1) { + this._classNames.push(className); + } }, remove: function () { this._classNames.forEach(className => { @@ -31,6 +33,8 @@ this._classNames.forEach((className, index) => { var $el = this._$els[index]; + // Avoid updating elements that are no longer present. + // elements removed will still exist in memory but won't be attached to the DOM any more if (global.document.body.contains($el.get(0))) { $el.addClass(className); }