2017-12-16 3 views
2

私はactiveを私のクラスに定義します。 Dragulaコード内のactiveの値にアクセスしたいと思います。私がconsole.log私のthis.active私はundefinedを得るとき。私のコードのこの時点では、thisは私のクラスの開始時に宣言した変数ではなく、私のDragulaオブジェクトを参照しているようです。dragulaService.setOptions内のthisの値にアクセスする

Dragulaコード内でactiveの値にアクセスするにはどうすればよいですか?

export class GamePage { 

    active = []; 
    inactive = []; 

    constructor() { 

    this.dragulaService.setOptions('drop-'+this.tableID, { 
     revertOnSpill: true, 
     direction: 'horizontal', 
     moves: (el, source, handle, sibling) => this.checkPlayerCanBeDragged(el.id), 
     accepts: function (el, target, source, sibling) { 

     console.log('inactive', this.inactive); 

     return true; 

     }  
    }); 

    } 

} 
+0

https://stackoverflow.com/questions/34361379/arrow-function-vs-function:あなたは "この" のいずれかのJavascriptのbindメソッドまたはコールバックとをバインドする必要があります-declaration-expressions-are-they-equivalent-exch –

+0

TL; DR:定義:太い矢印の機能を使用して定義する –

答えて

2

"this"のスコープは、クラス内のスコープとは異なります。

function (el, target, source, sibling) { 

    console.log('inactive', this.inactive); 

    return true; 

    }.bind(this); 

または

function (el, target, source, sibling,() => { 

    console.log('inactive', this.inactive); 

    return true; 

    }); 
+0

これは素晴らしいことです - 私は元の質問に対して行ったコメントを読んで、何をすべきか解読しようとしていました。あなたの提案は完璧に動作します、ありがとうございます。 – Chris

関連する問題