0

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<barDivs.length; 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:

<div id="foo1" class="bar">Click me!</div>
<div id="foo2" class="bar">No, click me!</div>

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.

TobyRush
  • 654
  • 4
  • 20
  • 1
    the problem here is not the preserving of the this reference, but that the function is assigned `after` the use in the addEventListener – TheGr8_Nik Aug 03 '15 at 12:23
  • 2
    the working example https://jsfiddle.net/sqq7tzLj/1/ note the event is `mousedown` without camel case ;-) – TheGr8_Nik Aug 03 '15 at 12:25
  • 2
    @TheGr8_Nik You've also passed a non-negative integer to `new Array()`, which is a pretty important difference to mention. – Anthony Grist Aug 03 '15 at 12:27
  • @AnthonyGrist - You are right, but wrong event is harder error to find because of no errors are generated. Tanks anyway for pointing it out :-) – TheGr8_Nik Aug 03 '15 at 12:31
  • @TheGr8_Nik True, that's the harder to find error. That said, if they were going to find the issue on the very first line of code for themselves, I feel like they would have done so *before* asking the question. – Anthony Grist Aug 03 '15 at 12:44
  • Thanks, Nik and Anthony. The camel caps and negative array parameter were typos from creating the JSFiddle, so I appreciate you calling those out and saving me the added trouble. – TobyRush Aug 03 '15 at 13:54

0 Answers0