Alon
Alon

Reputation: 7758

How do I pass function as a parameter in javascript

I have a pop up dialog box and I am trying to make it as dynamic as I can so I can send to it any function I want. I wanted to create a callback function so I can pass any function I want and it will do whatever I need on my object (in this example just print something for testing it.

here is what happens when the pop up is being called:

function DisplayPopUp(obj, callback) {


    //On Action Clicked
    $('#actionButton').click(function(e){
       e.preventDefault();
       callback(Obj);
    });
}

And here is the function that activates the PopUp function

$('.delete').click(function(){
    var obj="something something";
    DisplayPopUp(obj,function(){console.log('going to delete');});
});

Somehow that doesn't work and I get from firebug this error:

Obj is not defined

Clearly I do not transfer my function right - how should I do it?

Upvotes: 0

Views: 152

Answers (4)

jfriend00
jfriend00

Reputation: 707238

I see multiple possible issues with this code:

First, the case of Obj is wrong. It should be this:

function DisplayPopUp(obj, callback) {

    //On Action Clicked
    $('#actionButton').click(function(e){
       e.preventDefault();
       callback(obj);
    });
}

But, second I don't think you're using event handlers properly. You're calling DisplayPopup from a click handler. But, in that click handler, you're installing another click handler on another object. Is that really what you want to do? Unless you've left a bunch of code out of here that creates/destroys actionButton or unbinds click handlers, you can easily end up with multiple click handlers on #actionButton each time a delete button is clicked.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385114

Well, Obj is not defined. It should be obj.

The first thing you should do when you get an error message is to read it. :)

Upvotes: 1

BZink
BZink

Reputation: 7947

You're calling callback(Obj) but your variable name is obj. Check your case.

Upvotes: 2

pholser
pholser

Reputation: 4937

When you invoke the callback in DisplayPopup(), pass the parameter obj, not Obj.

Upvotes: 1

Related Questions