Skip to content

Instantly share code, notes, and snippets.

@tetsuharuohzeki
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tetsuharuohzeki/5477737dedfeb8ecec68 to your computer and use it in GitHub Desktop.
Save tetsuharuohzeki/5477737dedfeb8ecec68 to your computer and use it in GitHub Desktop.
inspired by Android Activity's Lifecycle
export interface Context {
onActivate(mountpoint: Element): void;
onDestroy(mountpoint: Element): void;
onSuspend(mountpoint: Element): void;
onResume(mountpoint: Element): void;
}
export class ContextStack {
private _mountPoint: Element;
private _stack: Array<Context>;
constructor(mountpoint: Element) {
this._mountPoint = mountpoint;
this._stack = [];
}
currentContext(): Context {
var stack = this._stack;
if (stack.length === 0) {
return null;
}
return stack[stack.length - 1];
}
replaceContext(aNew: Context): void {
var stack = this._stack;
var mountpoint = this._mountPoint;
var current = stack.pop();
if (!!current) {
current.onDestroy(mountpoint);
}
aNew.onActivate(mountpoint);
stack.push(aNew);
}
pushContext(aNext: Context): void {
var mountpoint = this._mountPoint;
var stack = this._stack;
var last = stack[stack.length - 1];
if (!!last) {
last.onSuspend(mountpoint);
}
stack.push(aNext);
aNext.onActivate(mountpoint);
}
popContext(): void {
var mountpoint = this._mountPoint;
var stack = this._stack;
if (stack.length === 0) {
return;
}
var last = stack.pop();
last.onDestroy(mountpoint);
var next = stack[stack.length - 1];
if (!!next) {
next.onResume(mountpoint);
}
}
destroy(): void {
var mountpoint = this._mountPoint;
var stack = this._stack;
for (var i = 0, l = stack.length; i < l; ++i) {
var ctx = stack[i];
stack[i] = null;
ctx.onDestroy(mountpoint);
}
this._mountPoint = null;
this._stack = null;
Object.freeze(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment