Reputation: 757
I am writing an Android app with Phonegap and its sqlite API. Now I want to insert a record if some conditions are met in a previous query. For example,
tx.executeSql("SELECT * FROM T_Task WHERE is_valid=1",[], successCB, errorCB);
In successCB, I want to add sub task if the task date is today and the sub task is not added for today yet. The condition to check if the task already exists is by task title.
function successCB(tx,results){
for(var i=0; i<results.rows.length; i++){
var item=results.rows.item(i);
if(item.date==today){//'today' is defined elsewhere, globally accessible
var sql="SELECT * FROM T_SubTask WHERE title='"+item.title+"' and date='"+today+"')";
tx.executeSql(sql,[],function(tx,results){addSubTask(tx, results, item.title)},errorCB);
}
}
Now the problem is if there are multiple tasks, the passing parameter item.title will be overridden by the last loop. I know I can use something like (function(x){FUNCTION(x)})(item.title) to avoid similar issues. But I don't know how to do it in the sqlite case, where I want to pass the correct 'item.title' and 'results' parameters both. If I use
tx.executeSql(sql,[],function(tx,results){ (function(x){addSubTask(tx, results, x)})(item.title),errorCB);
, another problem is the results will be the input parameter of "successCB(tx, results)", not the results object for the "FROM T_SubTask" query.
How can I make everything correct here?
Upvotes: 1
Views: 1299
Reputation: 350
The problem with results
can be easily fixed by changing the name of the argument to the anonymous success function in the "FROM T_SubTask" query.
As for the item variable, you should be able move the code inside the if
block into a separate function. Something like:
function addSubtaskIfNeeded(item, tx) {
var sql="SELECT * FROM T_SubTask WHERE title='"+item.title+"' and date='"+today+"')";
tx.executeSql(sql,[],function(tx,subresults){addSubTask(tx, subresults, item.title)},errorCB);
}
Note, that the results
variable is also renamed to subresults
above. Then change the code inside the if block to call that function:
if (item.date == today) {
addSubtaskIfNeeded(item, tx);
}
This way the item
variable inside addSubtaskIfNeeded
query callback function will be the one passed as argument to the function.
Upvotes: 1