Skip to content Skip to sidebar Skip to footer

Simple Javascript To Mimic Jquery Behaviour Of Using This In Events Handlers

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); //d

Solution 1:

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
}

Post a Comment for "Simple Javascript To Mimic Jquery Behaviour Of Using This In Events Handlers"