Meteor js Classes and contet

时间:2016-02-21 04:43:40

标签: javascript node.js class meteor

我试图在我的项目中使用meteor类。在我的课程中使用npm模块nodemailer,它提供了一个自定义处理程序来设置套接字,如下所示:

var nodemailer = require('nodemailer');

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

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

所以我试着用类:

将它包含在流星代码中
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
    }
}

问题是,当从模块调用transport.getSocket时,我将使用所有变量和方法丢失类上下文。有没有办法将模块函数附加到类对象方法,而不会丢失类上下文?

1 个答案:

答案 0 :(得分:1)

这应该适用于Function.prototype.bind()。试试这个:

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

这可能是也可能不是在这里使用bind的正确方法,但希望这会引导你走向正确的方向。