dagatsoin
dagatsoin

Reputation: 2656

How to pass a context (this) in a Tracker.autorun function?

This class will display this = undefined. How to pass the context in?

class MeteorAccount implements IService{

  constructor() {
    Tracker.autorun(function () {
      //observe
      Meteor.userId());
      console.log(this);//undefined
    });
  }

}

Upvotes: 1

Views: 225

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164467

You have two options:

The Function.bind function:

class MeteorAccount implements IService{
    constructor() {
        Tracker.autorun(function() {
            //observe
            Meteor.userId());
            console.log(this);//undefined
        }.bind(this));
    }
}

Or the arrow function:

class MeteorAccount implements IService{
    constructor() {
        Tracker.autorun(() => {
            //observe
            Meteor.userId());
            console.log(this);//undefined
        });
    }
}

Edit

There's another option, I just don't like it, but it's how people used to do it before the arrow function (not sure why not the bind option):

class MeteorAccount implements IService{
    constructor() {
        var self = this;
        
        Tracker.autorun(function() {
            //observe
            Meteor.userId());
            console.log(self);//undefined
        });
    }
}

Upvotes: 2

Related Questions