如何传递窗口:使用@HostListener滚动目标以触发Observable.fromEvent()订阅?

时间:2016-09-07 06:48:32

标签: javascript angular javascript-events rxjs observable

我希望保留@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;
    }
}

2 个答案:

答案 0 :(得分:4)

我想它应该是

var source = Observable.fromEvent(window, 'scroll');

答案 1 :(得分:0)

我发现这很有用:

Observable.fromEvent(window, 'wheel')