views:

102

answers:

2

I have a js function which has, until now, always been the callback for a click event, and therefore relies heavily on the 'this' pseudo-variable. 'this' is a <li> element.

However I now have a circumstance where it is sometimes triggered using more convoluted route, and in these circumstances 'this' is an entirely different element. However, before calling the function I am able to find the relevant <li>, but is there a way I can feed this in as 'this'? I thought of using .each() on the <li>, but it won't work on a single element.

edit it turns out that each() does work on single elements.. the error turned out to be something else.

Haven't deleted this question though as it could be useful to others

+2  A: 

You are looking for the call method:

function onClick() {
    console.log(this); // will be the #test element in both cases
    return false;
}

$('#test').click(onClick);

$('#test2').click(function() {
    onClick.call($('#test')[0]);
    return false;
});

Although this is also possible with apply:

onClick.apply($('#test')[0]);

The [0] is necessary to pass the actual DOM element instead of the jQuery wrapped set.

Paolo Bergantino
A: 

try using jquery.callback plugin. It keeps the context of callback.

xandy