Having trouble wrapping a DB object
Fairly new to JavaScript, so apologies if I'm missing something. I'm trying to wrap a DB connection in an abstraction layer with some helper functions, but I can't seem to apply arguments to the execute method:
// make a fake db con which works fine
var deeb = {
execute: function () {
debug("executing");
}
}
// a wrapper
DB = function (db) {
debug(typeof db);
debug(typeof db.execute);
db.execute.apply(null, ["select * from foo"]);
return db;
};
// this works, displays:
//[DEBUG] [16,603] object
//[DEBUG] [1,604] function
//[DEBUG] [1,605] executing
var db = DB(deeb);
// this fails with:
//[DEBUG] [1,732] object
//[DEBUG] [6,738] function
//[DEBUG] [239,981] Cannot call property apply in object
//ti.modules.titanium.database.TiDatabaseProxy@4377ad08.
// It is not a function, it is "object".
var deeb2 = Ti.Database.install("nt", "mydb2");
try {
var db2 = DB(deeb2);
} catch (e) {
debug(e.message);
}
3 Answers
-
Accepted Answer
I've been looking for a solution for this as well, and I think I've found one. the apply function for execute() is not implemented, so you can do it manually with the following code:
if (typeof db.execute.apply !== 'function') { db.execute.apply = Function.prototype.apply; } var rows = db.execute.apply(db, arguments);
-
To clarify, I want this so I can add some helper functions like:
function scalar() { var r = self.execute.apply(arguments); return r.isValidRow() ? r.field(0) : null; }
It seems like the execute() method lacks any prototype, so it's not inheriting apply(). I fiddled around with manually assigning a prototype, but I don't know enough about JS to see that through.
On Android in case that's relevant.
-
I believe this is a bug in the binding code. It happens on iPhone too. For now I've had to resort to an ugly switch() statement on the argument length and manually apply the args.