import EventEmitter from "./event-emitter"; import { LOADED, LOADING } from "../constant/context"; import { Mode, Platform } from "../types/page"; /** * page render context */ export default class Context extends EventEmitter { public $mode: Mode; public $platform: Platform; // 渲染状态队列 private $loadingQueue: Array = []; private $loadedQueue: Array = []; public $mixins: Record[] = []; // 页面数据源 // private $source: Record = {}; constructor(mode: Mode = "edit", platform: Platform = "auto") { super(); this.$mode = mode; this.$platform = platform; } /** * 设置mode * @param mode */ setMode(mode: Mode) { if (mode) { this.$mode = mode; } } /** * 设置platform * @param platform */ setPlatform(platform: Platform) { if (platform) { this.$platform = platform; } } /** * 全局混入 * @param mixin */ addMixins(mixin: Record) { if (this.$mixins.indexOf(mixin) === -1) { this.$mixins.push(mixin); } } /** * 执行全局混入方法 * @param name * @param args */ invokeMixin(name: string, ...args: any[]) { this.$mixins.forEach((mixin) => { if (typeof mixin[name] === "function") { mixin[name].apply(null, args); } }); } /** * 重置 */ public reset() { this.removeAllListener(); this.$loadingQueue = []; this.$loadedQueue = []; } /** * 创建加载组价记录 * @param uid */ public createLoading(uid: string) { this.$loadingQueue.push(uid); this.emit( LOADING, uid, Math.ceil( (this.$loadedQueue.length * 100) / (this.$loadingQueue.length + this.$loadedQueue.length) ) ); return () => { this.$loadedQueue.push(uid); this.$loadingQueue = this.$loadingQueue.filter((_uid) => _uid !== uid); let type: string = LOADING; if (this.$loadingQueue.length === 0) { type = LOADED; } this.emit( type, uid, Math.ceil( (this.$loadedQueue.length * 100) / (this.$loadingQueue.length + this.$loadedQueue.length) ) ); }; } }