Javascript closure scoping issue
Asked Answered
S

1

0

I'm trying to get a reference to cell and it appears null. If I'm understanding it correctly, I should be able to reference the variable. Correct?

$('td[someAttr]').mouseenter(function(cell) {
    var timeoutId = setTimeout(function() {
        // what should variable cell be? 
    }, 1000);
});

OR

$('td[someAttr]').mouseenter(function(cell) {
    var timeoutId = setTimeout(function() {
        // what should variable cell be? 
    }, 1000, cell);
});

UPDATE: This was obvious but the reason I asked this was because cell.pageX would be undefined if you had:

$('td[someAttr]').mouseenter(function() {
    var cell = this; //
    var timeoutId = setTimeout(function() {
        alert(cell.pageX); // cell.pageX will return null 
    }, 1000);
});

However, if you had:

$('td[someAttr]').mouseenter(function(cell) {
    alert(cell.pageX); // works fine as cell.pageX will have correct value.
});
Setback answered 25/6, 2009 at 21:23 Comment(0)
S
4

The context of the event handler is set to the element that triggered the event. You can get at it this way:

$('td[someAttr]').mouseenter(function() {
    var cell = this;
    var timeoutId = setTimeout(function() {
        alert(cell.tagName);
    }, 1000);
});

You may also want to wrap it as a jQuery object as well: var cell = $(this);

UPDATE: The first argument is the event object, not the element. The element is set as the context of the callback (i.e. this) and you can get access to the event object in exactly the way that you were in your example:

$('td[someAttr]').mouseenter(function(event) {
    var cell = this;
    var timeoutId = setTimeout(function() {
        alert(cell.tagName + ' ' + event.pageX);
    }, 1000);
});

Note that the "cell" element is also accessible as "event.target".

Scrooge answered 25/6, 2009 at 21:28 Comment(1)
This was obvious but the reason I asked this was because cell.pageX would be undefined, I'll post an update and show you what I mean.Setback

© 2022 - 2024 — McMap. All rights reserved.