feat: add init and ready lifecycles

This commit is contained in:
wuyue.xht 2020-04-19 22:36:58 +08:00
parent 2cf8573b78
commit fd100c9c3e

View File

@ -1,4 +1,5 @@
import { IAppConfig, IUtils, IComponents, HistoryMode } from '../run';
import EventEmitter from '@ali/offline-events';
interface IConstants {
[key: string]: any;
@ -100,15 +101,18 @@ export interface I18n {
type Locale = 'zh-CN' | 'en-US';
// export interface IProvider {
// init?(): void;
// getAppData?(appkey: string): Promise<IAppData | undefined>;
// getPageData?(pageId: string): Promise<ComponentModel | undefined>;
// getLazyComponent?(pageId: string, props: any): any;
// createApp?(): void;
// }
export interface IProvider {
init(): void;
ready(): void;
onReady(cb: any): void;
async(): Promise<IAppConfig>;
getAppData(): Promise<IAppData | undefined>;
getPageData(pageId: string): Promise<ComponentModel | undefined>;
getLazyComponent(pageId: string, props: any): any;
createApp(): void;
}
export default class Provider {
export default class Provider implements IProvider {
private components: IComponents = {};
private utils: IUtils = {};
private constants: IConstants = {};
@ -118,7 +122,10 @@ export default class Provider {
private history: HistoryMode = 'hash';
private containerId = '';
private i18n: I18n | null = null;
private homePage = '';
private lazyElementsMap: { [key: string]: any } = {};
private sectionalRender = false;
private emitter: EventEmitter = new EventEmitter();
constructor() {
this.init();
@ -153,8 +160,24 @@ export default class Provider {
});
}
async init() {
init() {
console.log('init');
// 默认 ready当重载了init时需手动触发 this.ready()
this.ready();
}
ready(params?: any) {
if (params && typeof params === 'function') {
params = params();
}
this.emitter.emit('ready', params || '');
}
onReady(cb: (params?: any) => void) {
if (!cb || typeof cb !== 'function') {
return;
}
this.emitter.on('ready', cb);
}
getAppData(): any {
@ -230,7 +253,7 @@ export default class Provider {
this.containerId = id;
}
setI18n(i18n: I18n) {
setI18n(i18n: I18n | undefined) {
if (!i18n) {
return;
}
@ -244,6 +267,16 @@ export default class Provider {
this.lazyElementsMap[pageId] = cache;
}
setHomePage(pageId: string) {
if (pageId) {
this.homePage = pageId;
}
}
setSectionalRender() {
this.sectionalRender = true;
}
getComponents() {
return this.components;
}
@ -305,10 +338,18 @@ export default class Provider {
return locale ? this.i18n[locale] : this.i18n;
}
getHomePage() {
return this.homePage;
}
getlazyElement(pageId: string) {
if (!pageId) {
return;
}
return this.lazyElementsMap[pageId];
}
isSectionalRender() {
return this.sectionalRender;
}
}