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!")}, functio开发者_高级运维n(){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)?
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);
}());
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
}
精彩评论