我正在使用以下代码调用函数db.transaction:
db.transaction(createSheetDB, function(){alert("Sheet creation error!")}, function(){alert("Sheet created!")});
函数createSheetDB是一个回调函数,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)?
答案 0 :(得分: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);
}());
答案 1 :(得分: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
}