0

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

Hansinger
  • 372
  • 1
  • 4
  • 14
  • You may want to consider skipping the DOM and creating a standalone event system using callbacks. I'm having a difficult time fully understanding what it is you are trying to do but it sounds like you may want to implement a reactor: https://gist.github.com/mohsen1/5123533 – BrianDiesel Jun 27 '16 at 22:40
  • 1
    [Don't iterate arrays using `for...in`](http://stackoverflow.com/q/500504/1529630) – Oriol Jun 27 '16 at 22:51

0 Answers0