在dragulaService.setOptions中访问this的值

时间:2017-12-16 17:20:56

标签: angular

我在班上定义active。我想在我的Dragula代码中访问active的值。当我console.log this.active时,我得到undefined。似乎在我的代码this的这一点上引用了我的Dragula对象,而不是我在课程开始时声明的变量。

如何在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;

      }      
    });  

  }

}

1 个答案:

答案 0 :(得分:2)

你"这个"的范围在函数中不同于类中的函数。你需要绑定"这个"使用Javascript的绑定方法或回调:

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;

  });