goh
goh

Reputation: 29511

"this" in jquery widget callback

I have the following widget

var a = $('#test').timetable({
            cell_click: openDialog
        });

whereby cell_click is an event generated by

_create:function(){ 
    dayBodyCells.click(function(){
            if( !$(this).hasClass('cell-inactive') ){
              var dic = self.getElementPos(this);
              self._trigger('cell_click', null,dic);        
        }
    });

and openDialog is the callback function. In the callback function for the dayBodyCells, i have this equaling the td element, which is what i expected. I'm curious - why does this inside function openDialog instead refers to #test?

Upvotes: 0

Views: 293

Answers (2)

Michael Lorton
Michael Lorton

Reputation: 44376

'Cause it just does? The this of any function is established at call-time, and the contract of an event-handler is that this is set to the DOM element that had event, not the object in which the event-handler could be found.

Consider the following:

b = "DOG".toLowerCase
console.log(b());

You might think this would print out "dog", but no. toLowerCase prints out the lower-case version of the String that this points to. When a function is called like that, this is set to undefined so you get

TypeError: can't convert undefined to object

(At least one Firefox -- afaik, every browser will fail in some fashion.)

Your confusion might be that this seems vaguely like a lexically-bound variable. It isn't, it's much closer to an ordinary function argument or the arguments list itself.

Upvotes: 0

Rob Cowie
Rob Cowie

Reputation: 22619

Within a bound event handler (callback), this refers to the element on which the event was triggered. So:

$('#myid').click(function(){
    // this is the #myid element
})

In your code, dayBodyCells must be a td (as you expect) therefore this refers to it in the click handler. However, when you trigger the cell_click event, you must be firing it from the #test element (via self._trigger).

If self._trigger('cell_click', null,dic) were replaced with $(this).trigger('cell_click', null,dic), this would then refer to the td within openDialog

Have a look at http://www.pkshiu.com/loft/archive/2009/01/understanding-this-this-and-event-in-a-jquery-callback-function and http://api.jquery.com/category/events/

Upvotes: 1

Related Questions