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');
}
}
}
答案 0 :(得分:3)