cugu
cugu

Reputation: 109

Correct callbacks and references for a PhoneGap-App

I want to create a PhoneGap-Application with multiple database tables that will be parsed into Javascript-Objects, so I wrote the following code.

$(document).ready( function(){      
    var startpage = Object.create(Persons);
    startpage.load();
});

var Page = {
    db: window.openDatabase("database", "1.0", "My Database", 200000),
    load: function(){
        this.db.transaction(this.queryDB, this.errorCB);
    },
    errorCB: function(err){
        alert("Error processing SQL: " + err.message);
    }
}

var Persons = Object.create(Page, {        
    queryDB: {
        value: function(tx){
            tx.executeSql(
                'SELECT * FROM PERSONS', 
                [], 
                this.createObjects,  <-- Problem is here
                this.errorCB
            );
        }
    },
    createObjects: {
        value: function(tx, results){
            // [...] parse results to objects
        }    
    }
});

The problem is that "this" in the queryDB-method is a reference to the method itself not to the Object. Does anyone know how I can reference the right method?

Thank you!

Upvotes: 0

Views: 231

Answers (1)

Simon MacDonald
Simon MacDonald

Reputation: 23273

You'll want to do something like what is discussed in this question:

What does 'var that = this;' mean in JavaScript?

So in Persons you will want to do a

var that = this;

and then refer to that.createObjects in your queryDB function.

Upvotes: 2

Related Questions