-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathglobal-utils.ts
More file actions
74 lines (69 loc) · 2.17 KB
/
Copy pathglobal-utils.ts
File metadata and controls
74 lines (69 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { Observable } from '../data/observable';
import { trace as profilingTrace, time, uptime, level as profilingLevel } from '../profiling';
// console.log('here in globals/global-utils!');
/**
* Manages internal framework global state
*/
export class NativeScriptGlobalState {
events: Observable;
launched = false;
// used by various classes to setup callbacks to wire up global app event handling when the app instance is ready
appEventWiring: Array<any>;
private _appInstanceReady = false;
private _setLaunched: () => void;
constructor() {
// console.log('creating NativeScriptGlobals...')
this.events = new Observable();
this._setLaunched = this._setLaunchedFn.bind(this);
this.events.on('launch', this._setLaunched);
if (profilingLevel() > 0) {
this.events.on('displayed', () => {
const duration = uptime();
const end = time();
const start = end - duration;
profilingTrace(`Displayed in ${duration.toFixed(2)}ms`, start, end);
});
}
}
get appInstanceReady() {
return this._appInstanceReady;
}
set appInstanceReady(value: boolean) {
this._appInstanceReady = value;
// app instance ready, wire up any app events waiting in startup queue
if (this.appEventWiring && this.appEventWiring.length) {
for (const callback of this.appEventWiring) {
callback();
}
// cleanup
this.appEventWiring = null;
}
}
/**
* Ability for classes to initialize app event handling early even before the app instance is ready during boot cycle avoiding boot race conditions
* @param callback wire up any global event handling inside the callback
*/
addEventWiring(callback: () => void) {
if (this._appInstanceReady) {
callback();
} else {
if (!this.appEventWiring) {
this.appEventWiring = [];
}
this.appEventWiring.push(callback);
}
}
private _setLaunchedFn() {
// console.log('NativeScriptGlobals launch fired!');
this.launched = true;
this.events.off('launch', this._setLaunched);
this._setLaunched = null;
}
}
export function getNativeScriptGlobals() {
if (!global.NativeScriptGlobals) {
// init global state handler
global.NativeScriptGlobals = new NativeScriptGlobalState();
}
return global.NativeScriptGlobals;
}