Vlado Pandžić
Vlado Pandžić

Reputation: 5058

Javascript - pass arguments to non-anonymous function

I have this function:

 $("#btn").click(function(e,someOtherArguments)
   {  //some code
    e.stopPropagation();});

It works, but If I have named function I can't use e because it is undefined.

var namedFunction= function(e,someOtherArguments) 
{
 //some code
  e.stopPropagation();
 }
$("#btn").click(namedFunction(e,someOtherArguments));

I would like to use this namedFunction because several buttons use it.

Upvotes: 2

Views: 654

Answers (3)

thinklinux
thinklinux

Reputation: 1377

You can use apply like so:

$("#btn").click(function(e,someOtherArguments){ 
  namedFunction.apply(this, arguments);
});

Upvotes: 0

PSR
PSR

Reputation: 40358

You can call that function directly in the click event

$("#btn").click(function(e,someOtherArguments){ 
  namedFunction(e, someOtherArguments);

}); 

Upvotes: 0

moonwave99
moonwave99

Reputation: 22820

Either:

$("#btn").click(namedFunction);

Or:

$("#btn").click(function(e,someOtherArguments){ 

  namedFunction(e, someOtherArguments);

});

Upvotes: 5

Related Questions