diff --git a/src/component/component.ts b/src/component/component.ts index 33a025d4..55b0fc87 100644 --- a/src/component/component.ts +++ b/src/component/component.ts @@ -84,6 +84,7 @@ interface Internal { observer: Observer | null; render: CompiledTemplate | null; mountedHandlers: { [key: number]: Function }; + willUnmountCB: Function | null; classObj: { [key: string]: boolean } | null; refs: { [key: string]: Component | HTMLElement | undefined } | null; } @@ -185,6 +186,7 @@ export class Component { currentFiber: null, boundHandlers: {}, mountedHandlers: {}, + willUnmountCB: null, observer: null, render: null, classObj: null, @@ -481,19 +483,22 @@ export class Component { } __owl__.isMounted = true; const handlers = __owl__.mountedHandlers; - for (let key in handlers) { - handlers[key](); - } try { this.mounted(); + for (let key in handlers) { + handlers[key](); + } } catch (e) { errorHandler(e, this); } } __callWillUnmount() { - this.willUnmount(); const __owl__ = this.__owl__; + if (__owl__.willUnmountCB) { + __owl__.willUnmountCB(); + } + this.willUnmount(); __owl__.isMounted = false; const children = __owl__.children; for (let id in children) { diff --git a/src/hooks.ts b/src/hooks.ts index a291c454..b69a505e 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -33,13 +33,11 @@ export function useState(state: T): T { * Mounted hook. The callback will be called when the current component is * mounted. Note that the component mounted method is called first. */ +let nextID = 1; + export function onMounted(cb) { const component: Component = Component._current; - const current = component.mounted; - component.mounted = function() { - current.call(component); - cb(); - }; + component.__owl__.mountedHandlers[`h${nextID++}`] = cb; } /** @@ -48,11 +46,15 @@ export function onMounted(cb) { */ export function onWillUnmount(cb) { const component: Component = Component._current; - const current = component.willUnmount; - component.willUnmount = function() { - cb(); - current.call(component); - }; + if (component.__owl__.willUnmountCB) { + const current = component.__owl__.willUnmountCB; + component.__owl__.willUnmountCB = function() { + cb.call(component); + current.call(component); + }; + } else { + component.__owl__.willUnmountCB = cb; + } } /** diff --git a/src/store/hooks.ts b/src/store/hooks.ts new file mode 100644 index 00000000..e69de29b diff --git a/tests/hooks.test.ts b/tests/hooks.test.ts index 0168330d..9bd0e01c 100644 --- a/tests/hooks.test.ts +++ b/tests/hooks.test.ts @@ -61,6 +61,8 @@ describe("hooks", () => { } const component = new MyComponent(env); await component.mount(fixture); + expect(component).not.toHaveProperty("mounted"); + expect(component).not.toHaveProperty("willUnmount"); expect(fixture.innerHTML).toBe("
hey
"); expect(steps).toEqual(["mounted"]); component.unmount();