Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an object inside a javascript event handler?

I am trying to get an object inside the onclick event handler function.

But it is not working the way I expect it to.

For example, if I run this code:

var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = function () { 
        console.log("this.id: " + this.id);
        console.log("entry.id: " + entry.id);
    };

}

What I expect is:

this.id: 1
entry.id: 1

this.id: 2
entry.id: 2

this.id: 3
entry.id: 3

But what I get is:

this.id: 1
entry.id: 3

this.id: 2
entry.id: 3

this.id: 3
entry.id: 3

Why is the entry object always the entry with the id 3?

How can I get the correct entry object inside the click event handler?

like image 975
Yaz Avatar asked Jan 19 '11 03:01

Yaz


People also ask

Can event handler return a value?

The standard signature of an event handler delegate defines a method that does not return a value. This method's first parameter is of type Object and refers to the instance that raises the event. Its second parameter is derived from type EventArgs and holds the event data.

Which are the event handlers supported by text object in JavaScript?

Solution. onBlur and onFocus are event/event handler used with text object in JavaScript.


1 Answers

One way to fix this is:

var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = (function (id) {
        return function () { 
            console.log("this.id: " + this.id);
            console.log("entry.id: " + id);
        };
    })(entry.id);

}

You can use a self-executing function (whose purpose is to provide a closure that entry.id will be bound to) to return you a new onclick handler that is bound to the particular id.

If you don't do this, all your onclick handlers get bound to the same entry variable and end up with the last value it received during the for loop.

like image 195
Ates Goral Avatar answered Nov 14 '22 22:11

Ates Goral