Tuesday, 3 January 2017

javascript - Can addEventListener point to an object's own function?

I don't know if this is a limitation of AddEventListener or if I just have a stupid error in my code. Assuming this JS in body.onload():




var barObjects = new Array(-1)

var barDivs = document.getElementsByClassName("bar");
for (var i=0; i barObjects.push(new barObject(barDivs[i]));
}

function barObject(whichDiv) {
this.myDiv=whichDiv;

whichDiv.addEventListener("mouseDown",this.clicked,false);

this.clicked = function(e) {
alert("clicked!");
}
}


and this HTML:




Click me!

No, click me!



How can I get this.clicked() to fire when the text is clicked?



Here it is as a JSFiddle. Thanks!



EDIT: While I'm sure this has been asked before, I couldn't find it, and the linked duplicate doesn't seem to be the same question at all unless I'm missing something big. Nik and Anthony's comments below solved the problem.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...