2017-05-04 72 views
0

我有這樣的聽者:角4:從全球聽者呼叫角功能

this.renderer.listenGlobal('document', 'mousemove', function(e: MouseEvent){ 

}); 

我,比如我有一個變量,我想從聽者設置,如:

AVariable:number; 

HelloWorld() { 
    this.renderer.listenGlobal('document', 'mousemove', function(e: MouseEvent){ 
     this.AVariable = 5; 
    }); 
} 

我將這個錯誤是未定義的。 我的問題是:我如何可以從列表器中調用變量/函數?

+0

問題解決了嗎? – echonax

回答

2

變化

'mousemove', function(e: MouseEvent){ 

'mousemove', (e: MouseEvent)=>{ 

如果使用functionthis將參照點擊事件實例(不渲染我想在這種情況下)

老js這樣做的方式是:

HelloWorld() { 
    var self = this; 
    this.renderer.listenGlobal('document', 'mousemove', function(e: MouseEvent){ 
     self.AVariable = 5; 
    }); 
} 
0

使用phatoarrow=>而不是直接調用函數,這將綁定到範圍this

HelloWorld() { 
    this.renderer.listenGlobal('document', 'mousemove', (e) => { 
     this.AVariable = 5; 
    }); 
} 
0

如果AVariable不是打字稿類誰擁有HelloWorld作爲一個成員函數中的一員,那麼你不應該使用這個。你應該只是調用變量:

this.renderer.listenGlobal('document', 'mousemove', function(e: MouseEvent){ 
     AVariable = 5; 
}); 

否則,以前的答案是你所需要的。