0

作爲NativeScript和Typescript的初學者我經常只是嘗試使用我在示例中找到的代碼。 現在我有一個組件生成一個Gridlayout並對手勢做出反應(例如滑動或平移)。簡化的代碼如下所示:Nativescript Angular:無法從函數內部讀取對象(this。undefined?)

import { Component, OnInit, ViewChild, ElementRef } from "@angular/core"; 
import { SwipeGestureEventData, GesturesObserver, GestureTypes, PanGestureEventData } from "ui/gestures"; 

export class CardComponent implements OnInit { 
    constructor() { } 
    prevDeltaX: number = 0; 

    ngOnInit() { 
     //initialising of the layout is unimportant 

     //Calls the funtion that creates the Layout and handles gestures 
     for (var key in this.SourceArray) { 
      this.handleSwipe(key); 
     } 
    } 

handleSwipe(key: any) { 
    // grid is this GridLayout Object created, cut out here 

    grid.on(GestureTypes.pan, function (args: PanGestureEventData) { 
     console.log(this.prevDeltaX); //Error here 
    }); 
} 

每當我刷卡,而不是顯示一個0功能在屏幕上,產生一個錯誤: TypeError: Cannot read property 'prevDeltaX' of undefined

聲明的對象handleSwipe函數內部用let prevDeltaX: number會的工作,不幸的是,我必須在其外部聲明對象,以便能夠更改分配的值並重新使用它。

問題:如何從Typescript中的函數中訪問(並更改)Object?

回答

2

使用arrow functions捕捉正確this

grid.on(GestureTypes.pan, (args: PanGestureEventData) => { 
    console.log(this.prevDeltaX); 
}); 

之所以箭頭功能的工作是因爲this不會裏面箭頭功能改變(即這將是CardComponent實例),其中作爲this將改變基於調用上下文,如果你使用function() {}

+0

工作。非常感謝您的解答和解釋! – R4h4

相關問題