qwr qwr
qwr qwr

Reputation: 1059

How to call a function from a function argument in JavaScript?

So I read the tutorial from some web, and they did something like this.

function populateDB(tx) {
     tx.executeSql('DROP TABLE IF EXISTS DEMO');
     tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

function errorCB(err) {
    alert("Error processing SQL: "+err.code);
}

function successCB() {
    alert("success!");
}

var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);

In the last line, they called the method transaction from object db, and there are 3 functions in the argument field, but isn't the functions populateDB, errorCB both need an argument as well? Where is that argument being called?

Upvotes: 0

Views: 192

Answers (4)

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28349

Those functions receive argument automatically based on the way the callback is designed. You pass in a reference to your function and when the callback uses that reference it populates the parameters based on how the whole mechanism is built. Basically the transaction Object knows to call methods for which you have supplied the reference and pass in whatever it intends to pass in. It's up to you to make sure to collect it (as you're doing).

The only reason this is a tad confusing is because you haven't cracked open the transaction Function. If you did, you'd see it calling those functions and passing in the values you are later collecting).

Upvotes: 1

jlengstorf
jlengstorf

Reputation: 447

Those are callbacks, which means that the transaction method will call one or the other CB functions dependent upon success or failure.

That method might work like this:

db.transaction = function(populateDB, errorCB, successCB) {
    // Try to do the requested action
    var tx = performTransaction(populateDB);

    // If the action failed, call the error callback, 
    // otherwise call the success callback
    if (tx==false) {
        var err = new TransactionError();
        return errorCB(err);
    } else {
        return successCB(tx);
    }
}

Upvotes: 2

shershen
shershen

Reputation: 9993

javascript has several methods to get/set data inside of the function, see: methods - call, apply and arguments var

Upvotes: 0

Pointy
Pointy

Reputation: 413720

The database runtime will call those functions when it wants to, and it will pass in the parameters. In the "db.transaction" function call, you're passing in references to the functions. At that point, function parameters are not needed because you're just identifying which functions to call.

Upvotes: 2

Related Questions