user1027620
user1027620

Reputation: 2785

Adding callback functionality to my simple javascript function

I am not writing a plugin. I am just looking for a simple clean way to let myself know when a certain function has finished executing ajax calls or whatever.

So I have this:

function doSomething() {
...
   getCauses("", query, function () {
       alert('test');  
   });
...
}

function getCauses(value, query) {
//do stuff...
}

Of course the alert never happens. I have a $.ajax call inside getCauses and would like to alert or do some action after getCauses finishes executing and then running the line of code from where the function was called.

Ideas? Thanks.

Upvotes: 1

Views: 389

Answers (3)

Bryan
Bryan

Reputation: 6752

Just using a bit of javascript trickery, here's an implementation that will allow you to implement some default functionality, in the case that no callback is defined. This would be great if 99% of the time you want a generic callback, and then you simply want to customize it in a few places.

var my_callback = function() {
    alert('I am coming from the custom callback!');
}

var special_function(string_1, callback) {
    (callback || function() {
        // Default actions here
        alert('I am coming from the generic callback');
    })();
}

// This will alert "I am coming from the custom callback!"
special_function("Some text here", my_callback);

// This will alert "I am coming from the generic callback"
special_function("Some text here");

// This will do nothing
special_function("Some text here", function() {});

Cheers!

Upvotes: 0

redhotvengeance
redhotvengeance

Reputation: 27866

You're passing your callback function but not executing it.

function doSomething() {
    ...
    getCauses("", query, function () {
        alert('test');  
    });
    ...
}

function getCauses(value, query, callback) {
    //do stuff...

    //stuff is done
    callback();
}

Upvotes: 0

Jacob
Jacob

Reputation: 78848

You first need to add the parameter to getCauses:

function getCauses(value, query, callback) {
}

Then, inside of your $.ajax call, call the callback parameter in your AJAX completion callback:

$.ajax({
    // ...
    complete: function() {
        // Your completion code
        callback();
    }
});

Upvotes: 2

Related Questions