Coding
Coding

Reputation: 134

Passing argument to indexedDB callback

I am pretty new to JS and even newer to indexedDB. My problem is that I need to refer to an object from within a callback function. Because "req.onsuccess" is not called synchron, "this" does not refer to a Groupobject. Thats why "this.units" and other variables are undefined. A very dirty workaround would be a global variable but I am just not willing to do that. Is there another way? Maybe passing an argument to the callback?

function Group(owner, pos)
{
    this.name = "";
    this.units = [];
    //...
}
Group.prototype.addUnit = function(unit)
{
    let req = db.transaction(["units"]).objectStore("units").get(unit);
    req.onsuccess = function(event)
    {
        let dbUnit = event.target.result;
        if (dbUnit)
        {
            this.units.push(dbUnit);//TypeError: this.units is undefined
            if (this.name == "")
            {
                this.name = dbUnit.name;
            }
        }
    };
};
myGroup = new Group(new User(), [0,0]);
myGroup.addUnit("unitname");

Thanks for helping!

EDIT

Using "bind(this)" solved the problem.

Group.prototype.addUnit = function(unit)
{
    let req = db.transaction(["units"]).objectStore("units").get(unit);
    req.onsuccess = function(event)
    {
        let dbUnit = event.target.result;
        if (dbUnit)
        {
            this.units.push(dbUnit);//TypeError: this.units is undefined
            if (this.name == "")
            {
                this.name = dbUnit.name;
            }
        }
    };
}.bind(this);

Upvotes: 1

Views: 498

Answers (1)

taile
taile

Reputation: 2776

So where's your onSucess? Let's try Bind, call, apply in JS. http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/.

Upvotes: 1

Related Questions