In a Choices JS component, whenever an item is removed from the list or an item is selected, the 'changes' event is fired. The problem is that if I remove an item I need to run a specific code and if I select an item I need to run a different code.
let selPaisDivisaoAdministrativa = $(this).find('.enderecamento-postal-sel-pais-div-administrativa')[0];
const choicePaisDivisaoAdministrativa = new Choices(selPaisDivisaoAdministrativa, {
// allowHTML: true,
placeholder: true,
renderChoiceLimit: -1,
position: 'auto',
//resetScrollPosition: true,
removeItemButton: true,
searchEnabled: true,
loadingText: 'Carregando...',
noResultsText: 'Nenhum resultado encontrado',
noChoicesText: 'Sem opções para escolher',
itemSelectText: 'Clique para selecionar'
});
choicePaisDivisaoAdministrativa.passedElement.element.addEventListener(
'change',
function (event) {
//code
if (event == 'change') {
}
else if (event == 'delete') {
}
else {
}
},
false,
);
Is there a way to check the source of the event, i.e. check if the event fired from the Delete Items button or if it fired because the item was changed? It would look something like the example below:
if (event == 'change') {
}
else if (event == 'delete') {
}
else {
}

The library documentation states that, in addition to the
changeevent, there are events foraddItemandremoveItem. We can attach event listeners for these events instead of thechangeone so that we know when items have been added or removed.The only challenge remaining is that the
removeItemevent, in addition to firing when we click the "X" button, will also fire when a new item is selected. In order for us to know that the selected item was removed via the "X" button, we can check the current selected value with thegetValuemethod. If the current value is undefined, it means the item was removed with the "X" button.