Question

I'm using jQuery and I have a function that serves as an event callback, and so in that function "this" represents the object that that captured the event. However, there's an instance where I want to call the function explicitly from another function - how do I set what "this" will equal within the function in this case?

For example:

function handleEvent(event) {
    $(this).removeClass("sad").addClass("happy");
}

$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        handleEvent(e); // in this case, "this" will be the window object
                        // but I'd like to set it to be, say, the input in question
    }
}
Was it helpful?

Solution

Use apply call.

handleEvent.call(this, e);

OTHER TIPS

Just parameterize the function you're interested in:

function doStuff(el) {
    $(el).removeClass("sad").addClass("happy");
}

function handleEvent(event) {
    doStuff(this);
}

$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        doStuff(this);
    }
}

Use

e.target

I'd advice you re-factoring your function as a jQuery plugin.

But here's a quick Fix:

handleEvent.apply(this,e) //transfers this from one scope, to another

If you're simply looking to call a single event handler as if it were being triggered normally, apply/call will work fine. However, depending on your needs, it may be more robust to use the zero-argument version of jQuery's click() function, which will trigger all click handlers for that element:

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        $(this).click(); // simulate a click
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top