Dusty
Dusty

Reputation: 125

Return parent function from child function on click

How can I return a parent function from a child function on click? Here's an example code:

function returnFunction() {

    var output = false;

    $('a').click(function() {

       output = true;

    });

    return output;    

}

var result = returnFunction();

The result will always be false since the click hasn't happened at the time the code is being run. How could I make this work though?

My intention is to call pop-up dialogs, and I'd like to have all the logic inside one function that can easily be loaded - including the click events of a Confirm dialog box.

Elsewhere in scripts I'd be calling it this way for example:

// Menu click triggers the dialog
$('a').click(function(e) {
    // The function displays the dialog and returns the click events of the dialog
    var result = returnFunction();
    // If result was false, we'll prevent the menu access, for example
    if (!result) {
        e.preventDefault();
    }
});

I'm aware of the jQuery UI dialog plugin. But I'd like to achieve this without it for now.

Thanks.

Upvotes: 1

Views: 4009

Answers (2)

Andrew Brock
Andrew Brock

Reputation: 1364

An over-simplification of it is:

Everything stops (including scrolling and clicking on hyperlinks) while executing javascript. This means you cannot "pause" the script until someone clicks on a link.

The typical way of solving this is a callback function:

function my_callback(some, arguments) {
    // you can do whatever in here: an ajax load, set a global variable, change some of the page, ...
    console.log(some, arguments);
    alert(some + " " + arguments);
}

function returnFunction(callback, param) {
    var output = false;
    $('a').click(function() {
       callback(param, "world");
    });
}

returnFunction(my_callback, "hello");

demo at http://jsfiddle.net/UnBj5/

EDIT:

I did mention global variables because they are an option, but they are typically bad style. Try to use other means if possible.

If you want more help with it, provide more details of what you are trying to do.

Upvotes: 2

ddoor
ddoor

Reputation: 5963

Try using parameters instead. Send a parameter to a function that shows your alert boxes, show a different pop-up alert depending on the parameter, what you are trying to do won't work because its basically a chicken-egg problem.

Upvotes: 0

Related Questions