5

我正在使用以下代码调用函数 db.transaction:

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

函数 createSheetDB 是一个回调函数,由 db.transaction() 隐式调用,db.transaction() 还向其传递参数 tx。我已经实现了这样的函数 createSheetDB(tx):

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)}
);}

现在的问题是 sheetName 和 desc 的值仅在调用函数中可用。如何将它们传递给函数 createSheetDB(tx)?

4

2 回答 2

3

您可以使用一种技术来创建一个新的回调,该回调将关闭您想要的变量。

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);

}());​
于 2012-09-16T01:53:41.867 回答
1

回调创建作为函数

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
}
于 2012-09-16T02:05:35.270 回答