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.

enter image description here

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 {

}
1

There are 1 best solutions below

1
76484 On BEST ANSWER

The library documentation states that, in addition to the change event, there are events for addItem and removeItem. We can attach event listeners for these events instead of the change one so that we know when items have been added or removed.

choicePaisDivisaoAdministrativa.passedElement.element.addEventListener('addItem', function (event) {                  
  console.log(`added: ${event.detail.value}`);
});

choicePaisDivisaoAdministrativa.passedElement.element.addEventListener('removeItem', function (event) {
  console.log(`removed: ${event.detail.value}`);
});

The only challenge remaining is that the removeItem event, 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 the getValue method. If the current value is undefined, it means the item was removed with the "X" button.

choicePaisDivisaoAdministrativa.passedElement.element.addEventListener('addItem', function (event) {                  
  console.log(`added: ${event.detail.value}`);
});

choicePaisDivisaoAdministrativa.passedElement.element.addEventListener('removeItem', function (event) {
  if (!choicePaisDivisaoAdministrativa.getValue()) {
    console.log(`removed: ${event.detail.value}`);
  }
});