From be9156d40f03eb729ec762b28e13a242e9e49de2 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Sun, 30 Jan 2022 13:05:58 +0000 Subject: [PATCH] Refactor dependant-selector further and (conditionally) update TomSelect if present I'm also introducing a convention here of adding a `private` comment to visually demarcate which methods are meant to be part of the public interface of the class and which aren't. The methods aren't *actually* private in any technical sense, it's just a bit of syntactic sugar to allow the intention to be communicated more clearly in the code's structure. --- .../dependant_select_controller.js | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/app/webpacker/controllers/dependant_select_controller.js b/app/webpacker/controllers/dependant_select_controller.js index f80a686bc6..daa615a7bf 100644 --- a/app/webpacker/controllers/dependant_select_controller.js +++ b/app/webpacker/controllers/dependant_select_controller.js @@ -8,16 +8,29 @@ export default class extends Controller { this.populateSelect(parseInt(this.sourceTarget.value)); } + // private + populateSelect(sourceId) { this.removeCurrentOptions() - - this.dependantOptionsFor(sourceId).forEach((item) => { - this.addOption(item[0], item[1]) - }); + this.populateNewOptions(sourceId) } removeCurrentOptions() { this.selectTarget.innerHTML = "" + + this.selectTarget.tomselect?.clear() + this.selectTarget.tomselect?.clearOptions() + } + + populateNewOptions(sourceId) { + const options = this.dependantOptionsFor(sourceId) + + options.forEach((item) => { + this.addOption(item[0], item[1]) + }); + + this.selectTarget.tomselect?.sync() + this.selectTarget.tomselect?.addItem(options[0]?.[1]) } addOption(label, value) {