2

首先,我很清楚zone.runOutsideAngular(callback),记录在这里

此方法的作用是在与 Angular不同的区域中运行回调。

我需要为document'smousemove事件附加一个非常快速的回调(以计算空闲时间)。我不想将整个 Zone.JS 任务机制附加到此特定回调的执行队列中。我真的很想让回调在普通的、未打补丁的浏览器运行时中运行。

我拥有的活动注册码是:

  private registerIdleCallback(callback: (idleFromSeconds: number) => void) {
    let idleFromSeconds = 0;
    const resetCounter = function() {
      idleFromSeconds = -1;
    };
    document.addEventListener('mousemove', resetCounter);
    document.addEventListener('keypress', resetCounter);
    document.addEventListener('touchstart', resetCounter);
    window.setInterval(function() {
      callback(++idleFromSeconds);
    }, 1000);
  }

问题是我怎样才能让这段代码使用unpatched document.addEventListener,实现与 Zone.JS 的完全分离和真正的原生性能?

4

2 回答 2

3

好吧,事实证明它很简单,但并不简单,所以我将在这里发布我找到的解决方案。

我想要做的是在Zone.JS 从浏览器的本机对象中修补地狱之前document.addEventListener在全局对象中保存一个可用的对象。

这必须在加载 polyfills 之前完成,因为 Zone 是在其中加载的。并且,它不能在 中以纯代码完成polyfills.ts,因为import语句在任何其他代码之前处理。

所以我需要zone-config.ts在同一文件夹中的文件polyfills.ts。在后者中,需要额外的导入:

import './zone-config'; // <- adding this line to the file, before...
// Zone JS is required by default for Angular itself.
import 'zone.js/dist/zone'; // Included with Angular CLI.

zone-config.ts我做花招:

(function(global) {
  // Save native handlers in the window.unpatched object.
  if (global.unpatched) return;

  if (global.Zone) {
    throw Error('Zone already running: cannot access native listeners');
  }

  global.unpatched = {
    windowAddEventListener: window.addEventListener.bind(window),
    windowRemoveEventListener: window.removeEventListener.bind(window),
    documentAddEventListener: document.addEventListener.bind(document),
    documentRemoveEventListener: document.removeEventListener.bind(document)
  };

  // Disable Zone.JS patching of WebSocket -- UNRELATED TO THIS QUESTION
  const propsArray = global.__Zone_ignore_on_properties || (global.__Zone_ignore_on_properties = []);
  propsArray.push({ target: WebSocket.prototype, ignoreProperties: ['close', 'error', 'open', 'message'] });

  // disable addEventListener
  const evtsArray = global.__zone_symbol__BLACK_LISTED_EVENTS || (global.__zone_symbol__BLACK_LISTED_EVENTS = []);
  evtsArray.push('message');
})(<any>window);

现在我有一个window.unpatched可用的对象,它允许我完全退出 Zone.JS,用于非常具体的任务,比如IdleService我正在处理的任务:

import { Injectable, NgZone } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

/* This is the object initialized in zone-config.ts */
const unpatched: {
  windowAddEventListener: typeof window.addEventListener;
  windowRemoveEventListener: typeof window.removeEventListener;
  documentAddEventListener: typeof document.addEventListener;
  documentRemoveEventListener: typeof document.removeEventListener;
} = window['unpatched'];

/** Manages event handlers used to detect User activity on the page,
 * either via mouse or keyboard events. */
@Injectable({
  providedIn: 'root'
})
export class IdleService {
  private _idleForSecond$ = new BehaviorSubject<number>(0);

  constructor(zone: NgZone) {
    const timerCallback = (idleFromSeconds: number): void => this._idleForSecond$.next(idleFromSeconds);
    this.registerIdleCallback(timerCallback);
  }

  private registerIdleCallback(callback: (idleFromSeconds: number) => void) {
    let idleFromSeconds = 0;
    const resetCounter = () => (idleFromSeconds = -1);

    // runs entirely out of Zone.JS
    unpatched.documentAddEventListener('mousemove', resetCounter);
    unpatched.documentAddEventListener('keypress', resetCounter);
    unpatched.documentAddEventListener('touchstart', resetCounter);

    // runs in the Zone normally
    window.setInterval(() => callback(++idleFromSeconds), 1000);
  }

  /** Returns an observable that emits when the user's inactivity time
   * surpasses a certain threshold.
   *
   * @param seconds The minimum inactivity time in seconds.
   */
  byAtLeast(seconds: number): Observable<number> {
    return this._idleForSecond$.pipe(filter(idleTime => idleTime >= seconds));
  }

  /** Returns an observable that emits every second the number of seconds since the
   * ladt user's activity.
   */
  by(): Observable<number> {
    return this._idleForSecond$.asObservable();
  }
}

现在,回调中的 stackTrace(idleFromSeconds = -1)根据需要为空。

希望这可以对其他人有所帮助:这并不复杂,但是将所有部分都准备好有点麻烦。

于 2019-10-28T00:18:36.267 回答
1

我不确定我是否得到了你想要做的事情。我做了一个小插曲,展示了如何从 Angular 外部进行事件回调。

https://stackblitz.com/edit/angular-s3krnu

于 2019-10-24T10:07:47.353 回答