这个关键字错了

时间:2016-09-16 16:19:14

标签: javascript angular typescript

this函数中的所有onScroll个关键字都变为错误this,在函数内部变为window这是有意义的。我想使用=>表示法来保留this,但在这种情况下,我似乎无法弄清楚正确的语法,或者甚至将它放在哪里使其正确。

this存储在public self = this中并不是出于某种奇怪的原因,但我更倾向于使用=>

的解决方案

这是班级:

export class ScrollXDirective implements AfterContentInit {
  @ContentChild(FormDatepickerPresetsComponent) presets: FormDatepickerPresetsComponent;

  public posX: number = 0;
  public offset: number = 35;

  constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}

  ngAfterContentInit() {

    let wrapper: HTMLElement = this.presets.presetsWrapperElement.nativeElement;
    let scrollHandler: string = 'DOMMouseScroll' in window ? 'DOMMouseScroll' : 'mousewheel';   

    this._renderer.listen(wrapper, scrollHandler, _.debounce(this.onScroll, 200));
  }

  onScroll(e: any) {

    e.preventDefault();

    let delta = (e.type === 'DOMMouseScroll' ? e.detail * -40 : e.wheelDelta);

    let list: HTMLElement = this.presets.presetsListElement.nativeElement;
    let totalWidth = list.offsetWidth;

    if (delta > 0) {

      if (this.posX >= 0) {
        return false;
      }

      this.posX = this.posX + this.offset;

      this._renderer.setElementStyle(list, 'margin-left', this.posX + 'px');
    }
    else {

      let listX = list.getBoundingClientRect().right;
      let hostX = this._elementRef.nativeElement.getBoundingClientRect().right;

      if (listX <= hostX) {
        return false;
      }

      this.posX = this.posX - this.offset;

      this._renderer.setElementStyle(list, 'margin-left', this.posX + 'px');
    }
  }
}

1 个答案:

答案 0 :(得分:3)

我认为它应该有效:

 _.debounce(this.onScroll.bind(this), 200)

另见文档 bind

另一种方式:

onScroll = (e: any) => {
  ...
}