Value:
@@ -15,7 +15,7 @@ export default class Counter extends Widget {
counter: 0
};
- constructor(parent: Widget, initialState?: number) {
+ constructor(parent: Widget | null, initialState?: number) {
super(parent);
this.state.counter = initialState || 0;
}
diff --git a/src/core/widget.ts b/src/core/widget.ts
index 24f66fb5..46d03707 100644
--- a/src/core/widget.ts
+++ b/src/core/widget.ts
@@ -25,7 +25,9 @@ export default class Widget {
this.parent = parent;
if (parent) {
parent.children.push(this);
- this.setEnvironment(parent.env);
+ if (parent.env) {
+ this.setEnvironment(parent.env);
+ }
}
}
@@ -46,16 +48,18 @@ export default class Widget {
target.appendChild(this.el!);
}
- destroy() {}
-
- setEnvironment(env: Env | null) {
- this.env = env ? Object.create(env) : null;
- if (this.env) {
- this.env.qweb.addTemplate(this.name, this.template);
- delete this.template;
+ destroy() {
+ if (this.el) {
+ this.el.remove();
}
}
+ setEnvironment(env: Env) {
+ this.env = Object.create(env);
+ env.qweb.addTemplate(this.name, this.template);
+ delete this.template;
+ }
+
async updateState(newState: Object) {
Object.assign(this.state, newState);
await this.render();
diff --git a/tests/widget.test.ts b/tests/widget.test.ts
index 88e2e3c7..8b7b1707 100644
--- a/tests/widget.test.ts
+++ b/tests/widget.test.ts
@@ -54,3 +54,42 @@ describe("basic widget properties", () => {
expect(target.innerHTML).toBe("
1
");
});
});
+
+describe("lifecycle hooks", () => {
+ test("willStart hook is called", async () => {
+ let willstart = false;
+ class HookWidget extends Widget {
+ async willStart() {
+ willstart = true;
+ }
+ }
+ const widget = makeWidget(HookWidget);
+ const target = document.createElement("div");
+ await widget.mount(target);
+ expect(willstart).toBe(true);
+ });
+
+ test("mounted hook is not called if not in DOM", async () => {
+ let mounted = false;
+ class HookWidget extends Widget {
+ async mounted() {
+ mounted = true;
+ }
+ }
+ const widget = makeWidget(HookWidget);
+ const target = document.createElement("div");
+ await widget.mount(target);
+ expect(mounted).toBe(false);
+ });
+});
+
+describe("destroy method", () => {
+ test("destroy remove the widget from the DOM", async () => {
+ const widget = makeWidget(Widget);
+ const target = document.body;
+ await widget.mount(target);
+ expect(document.contains(widget.el)).toBe(true);
+ widget.destroy();
+ expect(document.contains(widget.el)).toBe(false);
+ });
+});