Bind click event to function with parameters

Topics: General
Feb 4, 2014 at 7:01 PM
When I use code like this:
class A {
    constructor(b: B) {
        for (var i = 0; i < 10; i++) {
            var elem: HTMLElement = $("<div>" + i + "</div>")[0];
            var handler = b.bar.bind(b, i);
            elem.onclick = () => handler();
            $("body").append(elem);
        }
    }
}
class B {
    bar(foo:string) {
        console.log(foo);
    }
}

var a = new A(new B());
the console always logs 9 no matter where I click. I have no clue why this is happening, how can i get a seperate value into each clickevent?
Developer
Feb 4, 2014 at 10:55 PM
You're assigning a handler to elem.onclick, not adding one, so it's simply overwriting the previous handler each time through the loop. You need to use something that adds multiple event handlers like addEventListener.
Marked as answer by cheshirepuss42 on 2/4/2014 at 3:27 PM
Feb 4, 2014 at 11:27 PM
class A {
    constructor(b: B) {
        for (var i = 0; i < 10; i++) {
            var elem: HTMLElement = $("<div>" + i + "</div>")[0];
            elem.addEventListener("click", b.bar.bind(b, i));
            $("body").append(elem);
        }
    }
}
class B {
    bar(foo:string) {
        console.log(foo);
    }
}
var a = new A(new B());
You were right, this works. Thanks.