2016-02-21 53 views
3

我试图在我的项目中使用流星类。在使用NPM模块nodemailer它提供了一个自定义处理程序设置这样的插槽我班IM:流星js类和比赛

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

这应该是可行的Function.prototype.bind()。试试这个:

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

这可能会或可能不会在这里使用绑定的方法不对,但希望这将带领你进入正确的方向。

+0

感谢这帮助我。现在我开始了解如何解决上下文问题 – Vladislav