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???
In Javascript, you can call a function programmatically and tell it what
this
should refer to, and pass it some arguments using either thecall
orapply
method inFunction
. 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 whatthis
refers to inside that function.For example:
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)
.The distinction between using
call
orapply
to call the function is subtle. Withcall
the arguments will be passed as they are, and withapply
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.