Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a javascript-delegate with parameters?

Tags:

javascript

Lets say I have a javascript function call moveItem which takes two parameters source and destination.

I want to assign this function the the click-event of several buttons, each having different source and destinations.

OK, so without the parameter I would do something like this:

$('#myButton1').click(moveItem);

function moveItem() {
...
}

But what if moveItem looks like this:

function moveItem(source, destination) {
...
}

this doesn't seem to work:

$('#myButton1').click(moveItem('foo','bar'));
like image 951
nyn3x Avatar asked Jan 22 '23 17:01

nyn3x


2 Answers

You can't do quite what you want. You'll have to use an anonymous function to call moveItem:

$('#myButton1').click(function(){ moveItem('foo','bar'); };

When registering functions for events, the function signature has to match one of the supported signatures (because code in the click function is calling the handler). Since moveItem doesn't match, you have to wrap it in an anonymous function that does match.

like image 135
Justin Niessner Avatar answered Feb 04 '23 16:02

Justin Niessner


You want to do

$('#myButton1').click(function() {moveItem('foo','bar')});
like image 40
Jacob Mattison Avatar answered Feb 04 '23 14:02

Jacob Mattison