當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。