如何在Tracker.autorun函数中传递上下文(this)?

时间:2016-05-03 21:33:46

标签: meteor typescript reactive-programming

此课程将显示此= undefined。如何传递上下文?

class MeteorAccount implements IService{

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

}

1 个答案:

答案 0 :(得分:2)

您有两种选择:

Function.bind function

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

arrow function

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

修改

还有另一种选择,我只是不喜欢它,但它是人们在箭头功能之前用来做的事情(不知道为什么不是绑定选项):

class MeteorAccount implements IService{
    constructor() {
        var self = this;

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