From 3230f9bc4ac6f711c3da11aca9dac6486e6941d4 Mon Sep 17 00:00:00 2001 From: "JiaLi.Passion" Date: Sun, 15 Jan 2017 14:37:17 +0900 Subject: [PATCH] add runOutsideOfCurrentZone just like runOutsideOfAngular --- lib/zone.ts | 28 ++++++++++++++++++++++++++++ test/common/zone.spec.ts | 18 ++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lib/zone.ts b/lib/zone.ts index 522b56fd3..455c29c54 100644 --- a/lib/zone.ts +++ b/lib/zone.ts @@ -257,6 +257,13 @@ interface ZoneType { * Verify that Zone has been correctly patched. Specifically that Promise is zone aware. */ assertZonePatched(); + + /** + * Run function outside current zone, instead it will run under rootZone. + */ + runOutsideOfCurrentZone( + callback: Function, applyThis?: any, applyArgs?: any, source?: string, runGuarded?: boolean, + zoneSpec?: ZoneSpec): T; } /** @@ -564,6 +571,27 @@ const Zone: ZoneType = (function(global: any) { } } + static get rootZone(): AmbientZone { + let zone = Zone.current; + while (zone.parent) { + zone = zone.parent; + } + return zone; + } + + static runOutsideOfCurrentZone( + callback: Function, applyThis?: any, applyArgs?: any, source?: string, + runGuarded: boolean = true, zoneSpec?: ZoneSpec) { + let zone = Zone.rootZone; + if (zoneSpec) { + zone = zone.fork(zoneSpec); + } + if (runGuarded) { + return zone.runGuarded(callback, applyThis, applyArgs, source); + } else { + return zone.run(callback, applyThis, applyArgs, source); + } + } static get current(): AmbientZone { return _currentZoneFrame.zone; diff --git a/test/common/zone.spec.ts b/test/common/zone.spec.ts index 258f100ee..f6b63ee5b 100644 --- a/test/common/zone.spec.ts +++ b/test/common/zone.spec.ts @@ -83,6 +83,24 @@ describe('Zone', function() { }); }); + describe('run out side of current zone', function() { + it('should be able to get run under rootZone', function() { + Zone.current.fork({name: 'testZone'}).run(function() { + Zone.runOutsideOfCurrentZone(() => { + expect(Zone.current.name).toEqual(''); + }); + }); + }); + + it('should be able to get run outside of current zone', function() { + Zone.current.fork({name: 'testZone'}).run(function() { + Zone.runOutsideOfCurrentZone(() => { + expect(Zone.current.name).toEqual('newTestZone'); + expect(Zone.current.parent.name).toEqual(''); + }, null, null, null, true, {name: 'newTestZone'}); + }); + }); + }); describe('get', function() { it('should store properties', function() {