i want to bind an event handler to my (dynamic) javascript object, but it doesnt work how i think.
Do you have an idea how i could solve it?
What i want is to call an object function on a custom event. Or in other words i want to bind an event listener to an update function of my object.
For example i have my demo object:
var Demo = function (name) {
this.name = name;
var eventCounter = 0;
this.updateCounter = function () {
eventCounter++;
}
//...
};
Then i create multiple dynamic instances from it, like for example
var names = ["Jon", "Doe", "Max", "Mustermann"]
for(var i in names) {
new Demo(names[i])
}
and sometimes i want to update this Demo instance with a custom event.
document.dispatchEvent(new CustomEvent("CUSTOMEVENT"));
so my question is, how can i achieve something like the following
document.addEventListener("CUSTOMEVENT", function(){
// how to get the dynamic Demo instance?
// i want something like Demo.updateCounter()
});
My idea was to push the demo object into an array like
var names = ["Jon", "Doe", "Max", "Mustermann"]
var elementsToUpdate = [];
for(var i in names) {
elementsToUpdate[i] = new Demo(names[i])
}
and then in the event listener i can access them by
document.addEventListener("CUSTOMEVENT", function(){
elementsToUpdate[i].updateCounter()
});
But it feels a little ugly to me. So maybe there is a better solution for updating a dynamic instance of an object.
Thanks in advance