Vladislav
Vladislav

Reputation: 135

Meteor js Classes and contet

Im trying to use meteor classes in my project. In my class im using an npm module nodemailer which provides a custom handler for setting the socket like this:

var nodemailer = require('nodemailer');

var transport = nodemailer.createTransport({....});

transpot.getSocket = function (options, callback) {  // <-- here
   console.log('get socket');
}

So i tried to wrap it up in the meteor code with class:

var nodemailer = Meteor.npmRequire('nodemailer');

class TestNodemailerMeteor {

    constructor(options) {
           //....  
         this.name = options.name;
    }
    initMailer(){
        this.transport = nodemailer.createTransport({//set options});

        this.transport.getSocket = this.getSocket;


    }
    getSocket(options, callback){
          // 
         console.log(this.name); // this.name is undefined, lost this context here
    }
}

The problem is, when the transport.getSocket is getting called from the module, im loosing the class context with all the variables and methods. Is there a way to attach the module function to the class object method, without loosing class context?

Upvotes: 3

Views: 263

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21374

This should be doable with Function.prototype.bind(). Try this:

    this.transport.getSocket = this.getSocket.bind(this);

This may or may not be the right way of using bind here, but hopefully this will lead you into the right direction.

Upvotes: 1

Related Questions