Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass extra parameters to WebSQL callback function? [duplicate]

I am calling a function db.transaction with following code:

    db.transaction(createSheetDB, function(){alert("Sheet creation error!")}, function(){alert("Sheet created!")});

The function createSheetDB is a callback function which is implicitly called by db.transaction() which also passes it a parameter tx. I have implemented function createSheetDB(tx) like this:

function createSheetDB(tx) {
var nextId = getNextId();
tx.executeSql("INSERT INTO SHEET(id, name, desc) VALUES("+nextId+",'"+sheetName+"','"+desc+"')", [], 
        function(){alert("Sheet row inserted!")}, 
        function(tx, err){alert("Sheet row insertion Error: "+err.message+" "+err.code)}
);}

Now the problem is the values of sheetName and desc are available only in the calling function. How do I pass them onto function createSheetDB(tx)?

like image 499
Balkrishna Rawool Avatar asked Oct 06 '22 15:10

Balkrishna Rawool


2 Answers

You can use a technique whereby you create a new callback that will close over the variables you want.

function doStuff(callback) {
    var val = 43;
    callback(val);
}

function myCallback(val, anotherVal) {
    alert("val: " + val + "\nanotherVal: " + anotherVal);
}

(function() {

    var anotherVal = "Whoa!",
        anotherCallback = function(val) {
            return myCallback(val, anotherVal);
        };

    doStuff(anotherCallback);

}());​
like image 67
Josh Avatar answered Oct 10 '22 01:10

Josh


Callback creation as a function

function createSheetDB(sheetName, desc) {
    return function(tx){
        var nextId = 1;
        alert("INSERT INTO SHEET(id, name, desc) VALUES("+nextId+",'"+sheetName+"','"+desc+"')");
        /* delete above two lines and uncomment for your code
        var nextId = getNextId();
        tx.executeSql("INSERT INTO SHEET(id, name, desc) VALUES("+nextId+",'"+sheetName+"','"+desc+"')", [], 
            function(){alert("Sheet row inserted!")}, 
            function(tx, err){alert("Sheet row insertion Error: "+err.message+" "+err.code)}
        );
        */
    }
}

// dummy code to show as example
db = {transaction: function(fn,lose,win){return fn(),win();}};

function testIt(){
    var sheetName = 'hello',
        desc = 'world';
    db.transaction(createSheetDB(sheetName, desc), function(){alert("Sheet creation error!")}, function(){alert("Sheet created!")});
    // note how createSheetDB is now called with the vars you want
}
like image 30
Paul S. Avatar answered Oct 10 '22 02:10

Paul S.