mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-01-24 20:36:49 +00:00
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.
47 lines
1.1 KiB
JavaScript
47 lines
1.1 KiB
JavaScript
import { Controller } from "stimulus";
|
|
|
|
export default class extends Controller {
|
|
static targets = ["source", "select"];
|
|
static values = { options: Array };
|
|
|
|
handleSelectChange() {
|
|
this.populateSelect(parseInt(this.sourceTarget.value));
|
|
}
|
|
|
|
// private
|
|
|
|
populateSelect(sourceId) {
|
|
this.removeCurrentOptions()
|
|
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) {
|
|
const newOption = document.createElement("option")
|
|
newOption.innerHTML = label
|
|
newOption.value = value
|
|
this.selectTarget.appendChild(newOption)
|
|
}
|
|
|
|
dependantOptionsFor(sourceId) {
|
|
return this.optionsValue.find((option) => option[0] === sourceId)[1]
|
|
}
|
|
}
|