views:

113

answers:

1

This is not a question about jQuery, but about how jQuery implements such a behaviour.

In jQuery you can do this:

$('#some_link_id').click(function() 
{
   alert(this.tagName); //displays 'A'
})

could someone explain in general terms (no need you to write code) how do they obtain to pass the event's caller html elments (a link in this specific example) into the this keyword?

I obviously tried to look 1st in jQuery code, but I could not understand one line.

Thanks!

UPDATE: according to Anurag answer I decided to post some code at this point because it seems easier to code than what I thought:

function AddEvent(html_element, event_name, event_function)
{      
   if(html_element.attachEvent) //IE
      html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
   else if(html_element.addEventListener) //FF
      html_element.addEventListener(event_name, event_function, false); //don't need the 'call' trick because in FF everything already works in the right way         
}

and then now with a simple call we mimic jQuery behaviour of using this in events handlers

AddEvent(document.getElementById('some_id'), 'click', function()
{            
   alert(this.tagName); //shows 'A', and it's cross browser: works both IE and FF
}); 

Do you think there are any errors or something I misunderstood taking the all thing in a too superficial way???

+2  A: 

In Javascript, you can call a function programmatically and tell it what this should refer to, and pass it some arguments using either the call or apply method in Function. Function is an object too in Javascript.

jQuery iterates through every matching element in its results, and calls the click function on that object (in your example) passing the element itself as the context or what this refers to inside that function.

For example:

function alertElementText() {
    alert(this.text());
}

This will call the text function on the context (this) object, and alert it's value. Now we can call the function and make the context (this) to be the jQuery wrapped element (so we can call this directly without using $(this).

<a id="someA">some text</a>
alertElementText.call($("#someA")); // should alert "some text"

The distinction between using call or apply to call the function is subtle. With call the arguments will be passed as they are, and with apply they will be passed as an array. Read up more about apply and call on MDC.

Likewise when a DOM event handler is called, this already points to the element that triggered the event. jQuery just calls your callback and sets the context to the element.

document.getElementById("someId").onclick = function() {
    // this refers to #someId here
}
Anurag
Hmmmm... it seems pretty simple then. I updated the question according to your answer, I would like to hear your feedback.
Marco Demajo