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
}
}
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>
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