Preventing change event from being dispatched if value hasn't changed

This commit is contained in:
Ronan Berder
2025-06-30 19:46:59 +08:00
parent a1a74c220f
commit 608e3b2197
2 changed files with 18 additions and 28 deletions
+13 -16
View File
@@ -1,7 +1,7 @@
(() => {
const initSelect = (selectComponent) => {
const trigger = selectComponent.querySelector(':scope > button');
const selectedValue = trigger.querySelector(':scope > span');
const selectedLabel = trigger.querySelector(':scope > span');
const popover = selectComponent.querySelector(':scope > [data-popover]');
const listbox = popover.querySelector('[role="listbox"]');
const input = selectComponent.querySelector(':scope > input[type="hidden"]');
@@ -47,7 +47,7 @@
const updateValue = (option) => {
if (option) {
selectedValue.innerHTML = option.dataset.label || option.innerHTML;
selectedLabel.innerHTML = option.dataset.label || option.innerHTML;
input.value = option.dataset.value;
listbox.querySelector('[role="option"][aria-selected="true"]')?.removeAttribute('aria-selected');
option.setAttribute('aria-selected', 'true');
@@ -80,32 +80,29 @@
const selectOption = (option) => {
if (!option) return;
if (option.dataset.value != null) {
const oldValue = input.value;
const newValue = option.dataset.value;
if (newValue != null && newValue !== oldValue) {
updateValue(option);
}
closePopover();
const event = new CustomEvent('change', {
detail: { value: option.dataset.value },
bubbles: true
});
selectComponent.dispatchEvent(event);
};
const selectByValue = (value) => {
const option = options.find(opt => opt.dataset.value === value);
if (option) {
updateValue(option);
if (newValue !== oldValue) {
const event = new CustomEvent('change', {
detail: { value: option.dataset.value },
detail: { value: newValue },
bubbles: true
});
selectComponent.dispatchEvent(event);
}
};
const selectByValue = (value) => {
const option = options.find(opt => opt.dataset.value === value);
selectOption(option);
};
if (filter) {
const filterOptions = () => {
const searchTerm = filter.value.trim().toLowerCase();