Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
How to create a custom event that triggers when a variable changes

I am creating a custom widget with JavaScript and I need to create an event that triggers when a user changes a checkbox, for now I have a click event, but that doesn't work for what we want.

So I thought that creating a Custom Event is the way to go, and my idea is, I already have a variable that gets the value of the item that is selected, so I wanted to create a custom event that listen to this value and when it changes it will trigger the event. Don't know if this is the best way to do this, but this is my idea.

  this.addEventListener("selectedItem", event => {
    var eventSelectedItem = new CustomEvent("SelectedItem");
    console.log(selecteditem);
  })
    
function selecteditem(selectItem) {
  const selectedItem = _SelectItem // this is the variable that gets the value of the selected Item
    
    // now I don't know what to do here, I am reading a few things but this is the first time I am creating a custom event; 

    // I tried setters and getters but that I didn't understood how to make that work; 

    // Basically I need to save the last value and get the new value and then dispatch the event;
  
  selectItem.dispatchEvent(selecteditem);

}

Any help would be appreciated, either a new idea, or how to create this.


Edit to include more info.

let tmpl = document.createElement("template");
tmpl.innerHTML = '<div style="" id="root"></div>';

        class MultiInput extends HTMLElement {
          constructor() {
            super();
            
            _shadowRoot = this.attachShadow({ mode: "open" });
            _shadowRoot.appendChild(tmpl.content.cloneNode(true));
        
            this._export_settings = {};
        
            this.addEventListener("click", event => {
              var eventclick = new Event("onClick");
              this.dispatchEvent(eventclick);
            }); // This event works, but it triggers on all clicks (ofc) but it is not the event that I want
    
            this.addEventListener("change", event => {
              var eventchange = new Event("onChange");
              this.dispatchEvent(eventchange);
              console.log("Event is triggered");
            }); // This works only on textbox that I also have in the widget
          }
        }


    
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If I understand what you mean, this is simpler than creating an event. You just need to add the code in the function

document.querySelectorAll("input").forEach(item => {
  item.addEventListener("change", event => {
      // Add your code here
  })
})
<input type="checkbox" id="Hello">
<label for="Hello">Hello</label>
<br>
<input type="checkbox" id="World">
<label for="World"`enter code here`>World</label>

about 4 years ago · Juan Pablo Isaza Relatório

0

Well, with proxies you can track properties:

let obj = {
  myValue: 1
}

let proxy = new Proxy(obj, {
   get(obj, prop) {
      return obj[prop]
   },
   set(obj, prop, val){
      console.log("value changed")
      obj[prop] = val
   }
})


setInterval(() => {
   proxy.myValue++
},1000)

The set function is your trigger event, whenever you change your value proxy.myValue

Whenever the property value gets changed, the set function fires

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda