当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript rxjs.fromEvent函数代码示例

本文整理汇总了TypeScript中rxjs.fromEvent函数的典型用法代码示例。如果您正苦于以下问题:TypeScript fromEvent函数的具体用法?TypeScript fromEvent怎么用?TypeScript fromEvent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了fromEvent函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: map

export const ngbFocusTrap = (element: HTMLElement, stopFocusTrap$: Observable<any>, refocusOnClick = false) => {
  // last focused element
  const lastFocusedElement$ =
      fromEvent<FocusEvent>(element, 'focusin').pipe(takeUntil(stopFocusTrap$), map(e => e.target));

  // 'tab' / 'shift+tab' stream
  fromEvent<KeyboardEvent>(element, 'keydown')
      .pipe(
          takeUntil(stopFocusTrap$),
          // tslint:disable:deprecation
          filter(e => e.which === Key.Tab),
          // tslint:enable:deprecation
          withLatestFrom(lastFocusedElement$))
      .subscribe(([tabEvent, focusedElement]) => {
        const[first, last] = getFocusableBoundaryElements(element);

        if ((focusedElement === first || focusedElement === element) && tabEvent.shiftKey) {
          last.focus();
          tabEvent.preventDefault();
        }

        if (focusedElement === last && !tabEvent.shiftKey) {
          first.focus();
          tabEvent.preventDefault();
        }
      });

  // inside click
  if (refocusOnClick) {
    fromEvent(element, 'click')
        .pipe(takeUntil(stopFocusTrap$), withLatestFrom(lastFocusedElement$), map(arr => arr[1] as HTMLElement))
        .subscribe(lastFocusedElement => lastFocusedElement.focus());
  }
};
开发者ID:ExFlo,项目名称:ng-boostrap,代码行数:34,代码来源:focus-trap.ts

示例2: constructor

  /**
   * @constructor
   * @param {SourceBuffer} sourceBuffer
   */
  constructor(
    bufferType : IBufferType,
    codec : string,
    sourceBuffer : ICustomSourceBuffer<T>
  ) {
    this._destroy$ = new Subject<void>();
    this.bufferType = bufferType;
    this._sourceBuffer = sourceBuffer;
    this._queue = [];
    this._currentOrder = null;
    this._lastInitSegment = null;
    this._currentCodec = codec;

    // Some browsers (happened with firefox 66) sometimes "forget" to send us
    // `update` or `updateend` events.
    // In that case, we're completely unable to continue the queue here and
    // stay locked in a waiting state.
    // This interval is here to check at regular intervals if the underlying
    // SourceBuffer is currently updating.
    interval(SOURCE_BUFFER_FLUSHING_INTERVAL).pipe(
      tap(() => this._flush()),
      takeUntil(this._destroy$)
    ).subscribe();

    fromEvent(this._sourceBuffer, "error").pipe(
      tap((err) => this._onErrorEvent(err)),
      takeUntil(this._destroy$)
    ).subscribe();
    fromEvent(this._sourceBuffer, "updateend").pipe(
      tap(() => this._flush()),
      takeUntil(this._destroy$)
    ).subscribe();
  }
开发者ID:canalplus,项目名称:rx-player,代码行数:37,代码来源:queued_source_buffer.ts

示例3: getScrollAsStream

	// I return the current scroll percentage (0,100) of the given DOM node as a STREAM.
	// --
	// NOTE: The resultant STREAM is a COLD stream, which means that it won't actually
	// subscribe to the underlying DOM events unless something in the calling context
	// subscribes to the COLD stream.
	public getScrollAsStream( node: Target = document ) : Observable<number> {

		if ( node instanceof Document ) {

			// When we watch the DOCUMENT, we need to pull the scroll event from the
			// WINDOW, but then check the scroll offsets of the DOCUMENT.
			var stream = fromEvent( window, "scroll" ).pipe(
				map(
					( event: UIEvent ) : number => {

						return( this.getScroll( document ) );

					}
				)
			);

		} else {

			// When we watch an ELEMENT node, we can pull the scroll event and the scroll
			// offsets from the same ELEMENT node (unlike the Document version).
			var stream = fromEvent( node, "scroll" ).pipe(
				map(
					( event: UIEvent ) : number => {

						return( this.getScroll( node ) );

					}
				)
			);

		}

		return( stream );

	}
开发者ID:bennadel,项目名称:JavaScript-Demos,代码行数:40,代码来源:element-scroll-percentage.ts

示例4: fromEvent

    ngZone.runOutsideAngular(() => {
      this._change = _platform.isBrowser ?
          merge<Event>(fromEvent(window, 'resize'), fromEvent(window, 'orientationchange')) :
          observableOf();

      // Note that we need to do the subscription inside `runOutsideAngular`
      // since subscribing is what causes the event listener to be added.
      this._invalidateCache = this.change().subscribe(() => this._updateViewportSize());
    });
开发者ID:josephperrott,项目名称:material2,代码行数:9,代码来源:viewport-ruler.ts

示例5: sample3

 sample3() {
   const listener = merge(
     fromEvent(document, 'mousedown').pipe(mapTo(false)),
     fromEvent(document, 'mousemove').pipe(mapTo(true))
   )
     .pipe(sample(fromEvent(document, 'mouseup')))
     .subscribe(isDragging => {
       console.log('Were you dragging?', isDragging);
     });
 }
开发者ID:zwvista,项目名称:SampleMisc,代码行数:10,代码来源:filtering.service.ts

示例6: fromEvent

 protected connect$(
   instance: any,
   errorEvent = ERROR_EVENT,
   connectEvent = CONNECT_EVENT,
 ): Observable<any> {
   const error$ = fromEvent(instance, errorEvent).pipe(
     map(err => {
       throw err;
     }),
   );
   const connect$ = fromEvent(instance, connectEvent);
   return merge(error$, connect$).pipe(take(1));
 }
开发者ID:a1r0,项目名称:nest,代码行数:13,代码来源:client-proxy.ts

示例7: mergeMap

            mergeMap((node: {[key: string]: any}) => {
                const { key, applicationName, serviceType, isAuthorized, topCountNodes, hasAlert } = node;
                const isMergedNode = NodeGroup.isGroupKey(key);
                const serviceTypeImg = new Image();

                serviceTypeImg.src = ServerMapTheme.general.common.funcServerMapImagePath(serviceType);

                const serviceTypeImgLoadEvent$ = merge(
                    fromEvent(serviceTypeImg, 'load'),
                    fromEvent(serviceTypeImg, 'error').pipe(
                        switchMap(() => {
                            // 해당 serviceType 이름의 이미지가 없을 경우, NO_IMAGE_FOUND 이미지로 대체
                            const tempImg = new Image();

                            tempImg.src = ServerMapTheme.general.common.funcServerMapImagePath('NO_IMAGE_FOUND');
                            return fromEvent(tempImg, 'load');
                        })
                    )
                );
                const innerObs$ = iif(() => hasAlert && isAuthorized,
                    (() => {
                        const alertImg = new Image();

                        alertImg.src = ServerMapTheme.general.common.funcServerMapImagePath(ServerMapTheme.general.common.icon.error);
                        return zip(
                            serviceTypeImgLoadEvent$.pipe(pluck('target')),
                            fromEvent(alertImg, 'load').pipe(pluck('target'))
                        );
                    })(),
                    serviceTypeImgLoadEvent$.pipe(map((v: Event) => [v.target]))
                );

                return innerObs$.pipe(
                    map((img: HTMLImageElement[]) => {
                        const svg = ServerMapTemplate.getSVGString(img, node);

                        return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
                    }),
                    map((image: string) => {
                        return {
                            id: key,
                            label: isMergedNode ? this.getMergedNodeLabel(topCountNodes) : applicationName,
                            image,
                            group: key === baseApplicationKey ? 'main' : 'normal'
                        };
                    })
                );
            }),
开发者ID:young891221,项目名称:pinpoint,代码行数:48,代码来源:server-map-diagram-with-visjs.class.ts

示例8: bindMessageHandlers

  public bindMessageHandlers(
    client: any,
    handlers: MessageMappingProperties[],
    transform: (data: any) => Observable<any>,
  ) {
    const disconnect$ = fromEvent(client, DISCONNECT_EVENT).pipe(
      share(),
      first(),
    );

    handlers.forEach(({ message, callback }) => {
      const source$ = fromEvent(client, message).pipe(
        mergeMap((payload: any) => {
          const { data, ack } = this.mapPayload(payload);
          return transform(callback(data)).pipe(
            filter(response => !isNil(response)),
            map(response => [response, ack]),
          );
        }),
        takeUntil(disconnect$),
      );
      source$.subscribe(([response, ack]) => {
        if (response.event) {
          return client.emit(response.event, response.data);
        }
        isFunction(ack) && ack(response);
      });
    });
  }
开发者ID:SARAVANA1501,项目名称:nest,代码行数:29,代码来源:io-adapter.ts

示例9: fromEvent

			() => {

				var stream = fromEvent( document, "mousemove" ).pipe(
					// While the mouse-events are being triggered continuously on the
					// document (while the user is mousing-around), we only want to let
					// one event through every few seconds.
					throttleTime( 2000 ),
					map(
						( event: MouseEvent ) : MousePosition => {

							return({
								viewport: {
									x: event.clientX,
									y: event.clientY
								},
								document: {
									x: event.pageX,
									y: event.pageY
								}
							});

						}
					)
				);

				return( stream );

			}
开发者ID:bennadel,项目名称:JavaScript-Demos,代码行数:28,代码来源:app.component.ts

示例10: observableFromEvent

/**
 * Returns an observable which throws the right MediaError as soon an "error"
 * event is received through the media element.
 * @see MediaError
 * @param {HTMLMediaElement} mediaElement
 * @returns {Observable}
 */
export default function throwOnMediaError(
  mediaElement : HTMLMediaElement
) : Observable<never> {
  return observableFromEvent(mediaElement, "error")
    .pipe(mergeMap(() => {
      const errorCode = mediaElement.error && mediaElement.error.code;
      switch (errorCode) {
        case 1:
          throw new MediaError("MEDIA_ERR_ABORTED",
            "The fetching of the associated resource was aborted by the " +
            "user's request.", true);
        case 2:
          throw new MediaError("MEDIA_ERR_NETWORK",
            "A network error occurred which prevented the media from being " +
            "successfully fetched", true);
        case 3:
          throw new MediaError("MEDIA_ERR_DECODE",
            "An error occurred while trying to decode the media resource", true);
        case 4:
          throw new MediaError("MEDIA_ERR_SRC_NOT_SUPPORTED",
            "The media resource has been found to be unsuitable.", true);
        default:
          throw new MediaError("MEDIA_ERR_UNKNOWN",
            "The HTMLMediaElement errored due to an unknown reason.", true);
      }
    }));
}
开发者ID:canalplus,项目名称:rx-player,代码行数:34,代码来源:throw_on_media_error.ts


注:本文中的rxjs.fromEvent函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。