lboyel
lboyel

Reputation: 2228

Event reference is undefined on event listener callback passed as a method

Callback method is not being called when I attach my event to element. The method in question belongs to an object but it seems the way I am calling it the method isn't being called when the click event occurs.

 var myObject = {
     handledrop : function () {
          
         //retrieved created html element
         var elem = document.getElementById("required");
         elem.addEventListener("click", this.deleteFavorite.bind(this), false);
     },

     //this method isn't being called when click event occurs
     deleteFavorite: function (evt) {
        console.log(evt);
     }
 }

What am I doing wrong? How do I pass the right context so that the correct method is called and passed the right context which is event

Upvotes: 1

Views: 945

Answers (1)

Tim
Tim

Reputation: 549

Couple of debug/trouble-shooting tips:

  1. Post the html for the "required" element.
  2. Check that the "required" element you think you're getting is valid:

    var elem = document.getElementById("required");
    console.log('elem:',elem);
    
  3. You can also iterate its properties to ensure that function exists:

    foreach(var property in elem){
        console.log('property:',property);
    }
    

For cross browser support - you might want to read this post: addEventListener vs onclick

Upvotes: 1

Related Questions