简体   繁体   中英

How to get this.userId in function inside Meteor method

I need to call a few times a function for every user who is logged in, but when the function is placed inside meteor method, this.userId becomes undefined inside function scope, here's the example:

myMethod: function(){

  console.log(this.userId); // this returns proper userId

  function innerFunction(){
    console.log(this.userId); // this returns undefined
  };
  innerFunction();

}

How can I pass this.userId inside a function? Does a function has to be binded with Meteor.bindEnvironment?

You have some variants to resolve this:

  • use .bind() method:

     myMethod: function () { console.log(this.userId); // this returns proper userId function innerFunction() { console.log(this.userId); // this returns undefined } innerFunction.bind(this); } 
  • use .apply() method for applying correct this into function:

     myMethod: function () { console.log(this.userId); // this returns proper userId function innerFunction() { console.log(this.userId); // this returns undefined }; innerFunction.apply(this); } 
  • also you can just use that insted of this for pass the scope into in innerFunction :

     myMethod: function () { var that = this; console.log(this.userId); // this returns proper userId function innerFunction() { console.log(that.userId); // this returns undefined } innerFunction(); } 
  • or just pass userId into innerFunction

     myMethod: function () { var userId = this.userId; console.log(this.userId); // this returns proper userId function innerFunction(userId) { console.log(userId); // this returns undefined } innerFunction(); } 

There are a couple of ways you can do it:

myMethod: function () {
    var me = this;

    function innerFunction () {
        console.log(me.userId);
    };

    innerFunction();
}

or

myMethod: function () {
    var innerFunction = function () {
        console.log(this.userId);
    }.bind(this);

    innerFunction();
}

have you tried to bind the function ?

   myMethod: function(){

      console.log(this.userId); // this returns proper userId


  function innerFunction(){
    console.log(this.userId); // this returns undefined
  }.bind(this);
  innerFunction();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM