views:

44

answers:

2

I have something like this:

$('element.selector').live("click", function (){
 run_some_func ();
});

$('element.selector2').live("click", function (){
 run_some_func ();
});

Now in the function I need to use $(this):

function run_some_func () {
    $(this).show();
}

How do I get the function to know that $(this) is element.selector that is clicked?

Thanks.

+2  A: 

You can use the call function to change the context (set the this keyword) on the function you want to execute:

$('element.selector').live("click", function (){
  run_some_func.call(this); // change the context of run_some_func
});

function run_some_func () {
  // the this keyword will be the element that triggered the event
}

And if you need to pass some arguments to that function, you can:

run_some_func.call(this, arg1, arg2, arg3); // call run_some_func(arg1,arg2,arg3)
                                            // and change the context (this)
CMS
Thanks, this is exactly the sort of thing I want to learn.
Mark
A: 

Can't you pass $(this) to your function such that:

$('element.selector').live("click", function (){
        run_some_func ($(this));
});

..and then

run_some_func(obj){
    obj.do_something();
})
Colin