I have a problem with the following code:
var data = {};
$('table tr').each(function() {
var uid = $('td a', $(this)).attr('href').split('=')[1];
TTDB.transaction(
function (tx) {
tx.executeSql("SELECT id FROM players WHERE uid = ?;", [uid], function (txSub, results) {
data[uid] = results.rows.item(0).id;
}, TTDBerrorHandler);
}
);
});
$('#member tbody tr').each(function() {
var uid = $('td a', $(this)).attr('href').split('=')[1];
console.log(uid); // Returns correctly 1643 as shown below
console.log(data); // Returns whole object correctly
console.log(data['1643']); // Returns **undefined**
console.log(data[uid]); // Returns **undefined**
console.log(uid); // uid is still correctly set to 1643
/* Following from Safari console
1643
Object
156: 1
217: 17
295: 138
579: 136
764: 139
774: 142
816: 144
826: 14
955: 73
1096: 137
1133: 13
1134: 141
1232: 140
1321: 11
1643: 31
2307: 143
__proto__: Object
undefined
undefined
1643
*/
});
Here is a test set that works as it should.
var test = {};
test[156] = 1;
test[1643] = 31;
var testUid = 1643;
console.log(test);
console.log(test['1643']); // Returns correctly 31 as shown below
console.log(test[testUid]); // Returns correctly 31 as shown below
/* This is from Safari console
Object
156: 1
1643: 31
__proto__: Object
31
31
*/
As basically identical test set works, I guess the problem has something to do with local database's asynchronous operation, but I just can't figure out how to fix this...
UPDATE: To clarify my problem/what I'm trying to achieve.
For example if I have a table, which I iterate through and then want to add some fields with data from database.
<table>
<tr><td class="uid">123<td></tr>
<tr><td class="uid">234<td></tr>
</table>
Then I would want to add new columns to it:
$('table tr').each(function() {
var uid = $('td.uid', $(this)).text();
TTDB.transaction(
function (tx) {
tx.executeSql("SELECT id FROM players WHERE uid = ?;", [uid], function (txSub, results) {
// Problem is that because this transaction is asynchronous $(this) is
// not defined when this gets executed.
$(this).append('<td class="id">' + id + '</td>');
}, TTDBerrorHandler);
}
);
});