nyn3x
nyn3x

Reputation: 919

How to call a javascript-delegate with parameters?

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'));

Upvotes: 4

Views: 6093

Answers (3)

Andreas Köberle
Andreas Köberle

Reputation: 110922

$('#myButton1').click(function(){moveItem(source, destination)});

Upvotes: 1

Jacob Mattison
Jacob Mattison

Reputation: 51062

You want to do

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

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245429

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.

Upvotes: 7

Related Questions