我希望保留@HostListner
中使用的类似语法,并从该事件使用fromEvent()
创建流。目前,滚动不会触发fromEvent
订阅。
问题:
如何触发var source = Observable.fromEvent(target, 'window:scroll');
?
import { Directive, HostListener } from '@angular/core';
import {Observable} from "rxjs";
import 'rxjs/add/observable/fromEvent';
@Directive({
selector: '[mh-scroll]'
})
export class MhScroll {
lastKnownScrollPosition: number;
ticking: boolean;
constructor() {
this.lastKnownScrollPosition = 0;
this.ticking = false;
}
isElementCloseToTop(target) {
var source = Observable.fromEvent(target, 'window:scroll'); //this never triggers.
var subscription = source.subscribe(
(x) => {
console.log('Next: Clicked!');
},
(err) => {
console.log('Error: %s', err);
},
() => {
console.log('Completed');
});
this.ticking = false;
}
@HostListener('window:scroll', ['$event.target'])
triggeredScroll(target) {
this.lastKnownScrollPosition = window.scrollY;
if (!this.ticking) {
window.requestAnimationFrame(this.isElementCloseToTop.bind(this, target));
}
this.ticking = true;
}
}
答案 0 :(得分:4)
我想它应该是
var source = Observable.fromEvent(window, 'scroll');
答案 1 :(得分:0)
我发现这很有用:
Observable.fromEvent(window, 'wheel')