Chrillewoodz Chrillewoodz - 2 months ago 6
TypeScript Question

This keyword becomes the wrong this

All

this
keywords inside the
onScroll
function becomes the wrong
this
, inside the function it becomes the
window
which makes sense. I want to use the
=>
notation to preserve
this
but in this scenario I can't seem to figure out the correct syntax or where to even put it to make it right.

Storing
this
in a
public self = this
doesn't work either for some odd reason, but I would prefer a solution using
=>


Here's the class:

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');
}
}
}

Answer

I think it should work:

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

See also documentation bind

Another way:

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