Search code examples
javascripthtmlcallbackfunction-pointersaddeventlistener

Javascript addEventListener passing function pointer


i like to pass to a function pointer to function that the addEventListener will use . if you run this you will get an error .
what is the "Javascript" way to pass a function pointer ( don't know how to call it ) to addEventListener ?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="UTF-8">
    <title>Title</title>

    <style>

</style>
<script>
var data = {
    "foo1" : "aaa",
    "foo2" : "bbb",
    "foo3" : "ccc"
}
var createLabel = function(mykey,func) {
    var label = document.createElement('label');
             label.innerHTML = mykey;
             label.id = "lbl_"+mykey;
             label.addEventListener("click", () =>{
                    self.func(mykey);
         }, false);
         document.getElementById("container2").appendChild(label);
         var br = document.createElement('br');
         document.getElementById("container2").appendChild(br);
};
var popolateDS = function() {
    self = this;
    var i = 0;
    for(var key in data) {
     (function () {
        var mykey = key;
        if (data.hasOwnProperty(key)) {
            if(i==0) {
                createLabel(key,dsOnClick1);
                i++;
            }
            createLabel(key,dsOnClick2);
        }
      }()); // immediate invocation
    }
}

var dsOnClick1 = function(key)  {
    alert("dsOnClick1 "+key);
}
var dsOnClick2 = function(key)  {
    alert("dsOnClick2 "+key);
}

</script>
</head>
<body>
<div id="container2">
</div>

<button onclick="popolateDS()">click</button>




</body>
</html>


Solution

  • You don't need to refer to this as self.func, you can just call func like below and it'll work as expected:

    label.addEventListener("click", () =>{
      func(mykey);
    }, false);