Dariusz Sikorski
Dariusz Sikorski

Reputation: 4407

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?

Upvotes: 1

Views: 434

Answers (3)

Alex Filatov
Alex Filatov

Reputation: 2321

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

Upvotes: 2

Alex McMillan
Alex McMillan

Reputation: 17952

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

Upvotes: 1

Dan Kuida
Dan Kuida

Reputation: 1057

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

}

Upvotes: 0

Related Questions