From dad0122f11d813495cdabac47ea2c0321163c72b Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Fri, 12 Jun 2020 10:50:46 +0200 Subject: [PATCH] js: Introduce behavior complete.js --- public/js/icinga/behavior/complete.js | 82 +++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 public/js/icinga/behavior/complete.js diff --git a/public/js/icinga/behavior/complete.js b/public/js/icinga/behavior/complete.js new file mode 100644 index 000000000..5ac99ccbe --- /dev/null +++ b/public/js/icinga/behavior/complete.js @@ -0,0 +1,82 @@ +/* Icinga Web 2 | (c) 2020 Icinga GmbH | GPLv2+ */ + +/** + * Complete - Behavior for forms with auto-completion of terms + */ +(function(Icinga, $) { + + "use strict"; + + Icinga.Behaviors = Icinga.Behaviors || {}; + + /** + * @param icinga + * @constructor + */ + var Complete = function (icinga) { + Icinga.EventListener.call(this, icinga); + + this.on('beforerender', '.container', this.onBeforeRender, this); + this.on('rendered', '.container', this.onRendered, this); + + /** + * Cached completions + * + * Holds values only during the time between `beforerender` and `rendered` + * + * @type {{}} + */ + this.cachedCompletions = {}; + }; + Complete.prototype = new Icinga.EventListener(); + + /** + * @param event + */ + Complete.prototype.onBeforeRender = function (event) { + var _this = event.data.self; + + var $elements = $('input[data-term-completion]', event.currentTarget); + + // Remember current instances + $elements.each(function () { + var $input = $(this), + completion = $input.data('completion'); + if (completion) { + _this.cachedCompletions[_this.icinga.utils.getDomPath($input[0]).join(' ')] = completion; + } + }); + }; + + /** + * @param event + */ + Complete.prototype.onRendered = function (event) { + var _this = event.data.self; + + // Apply remembered instances + $.each(_this.cachedCompletions, function (inputPath) { + var $input = $(inputPath); + if ($input.length) { + this.refresh($input[0]); + } else { + this.destroy(); + } + + delete _this.cachedCompletions[inputPath]; + }); + + var $elements = $('input[data-term-completion]', event.currentTarget); + + // Create new instances + $elements.each(function() { + var $input = $(this); + if (! $input.data('completion')) { + (new Completion(_this.icinga, this)).bind().restoreTerms(); + } + }); + }; + + Icinga.Behaviors.Complete = Complete; + +})(Icinga, jQuery);