How to get this.userId in function inside Meteor method

巧了我就是萌 提交于 2019-12-24 16:57:09

问题


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?


回答1:


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 correctthis 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 thisfor 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();
    }
    



回答2:


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();
}



回答3:


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();

}


来源:https://stackoverflow.com/questions/30576136/how-to-get-this-userid-in-function-inside-meteor-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!