Search code examples
javascriptdomevent-delegation

Event Delegation with associated object for each DOM


I have a some DOM elements that are created dynamic with events and clousure.

Something like this:

    var container = document.getElementById("container");
    var objects = [{ name: "test" }, {name: "test2"}]
    for(var i = 0; i < objects.length; i+=1){
            var dom = document.createElement("div");
            dom.addEventListener("click", (function(obj){
                    return function(){
                            alert(obj.name);
                    };
            }(objects[i]), false);
            container.appendChild(dom);
    }

My question is how can I use event delegation to this? So all the click events are on the #container dom, but still have the obj-object associated with the dom.

I think I can use another object and use it as a "hash"-table, with the dom element and the obj, and then use e.target on the "hash"-table, but is there not a better solution?


Solution

  • In a nutshell (not tested) :

    var container = document.getElementById("container");
        var objects = [{ name: "test" }, {name: "test2"}]
        for(var i = 0; i < objects.length; i+=1){
                var dom = document.createElement("div");
                objects[i].instance = dom;
                container.appendChild(dom);
        }
    
    container.addEventListener("click",function(event){
          for(var i in objects){
          if(event.target == objects[i].instance){
           alert(objects[i].name);
           break;
          }
    }
    }, false);