add warning when rendering outside of render fn for templates

This commit is contained in:
Bruno Windels 2021-04-15 15:14:02 +02:00
parent 766ce4e217
commit 33f1ba686c

View file

@ -68,6 +68,7 @@ export class TemplateView extends BaseUpdateView {
mount(options) { mount(options) {
const builder = new TemplateBuilder(this); const builder = new TemplateBuilder(this);
try {
if (this._render) { if (this._render) {
this._root = this._render(builder, this._value); this._root = this._render(builder, this._value);
} else if (this.render) { // overriden in subclass } else if (this.render) { // overriden in subclass
@ -75,6 +76,9 @@ export class TemplateView extends BaseUpdateView {
} else { } else {
throw new Error("no render function passed in, or overriden in subclass"); throw new Error("no render function passed in, or overriden in subclass");
} }
} finally {
builder.close();
}
// takes care of update being called when needed // takes care of update being called when needed
super.mount(options); super.mount(options);
this._attach(); this._attach();
@ -145,6 +149,18 @@ export class TemplateView extends BaseUpdateView {
class TemplateBuilder { class TemplateBuilder {
constructor(templateView) { constructor(templateView) {
this._templateView = templateView; this._templateView = templateView;
this._closed = false;
}
close() {
this._closed = true;
}
_addBinding(fn) {
if (this._closed) {
console.trace("Adding a binding after render will likely cause memory leaks");
}
this._templateView._addBinding(fn);
} }
get _value() { get _value() {
@ -164,7 +180,7 @@ class TemplateBuilder {
setAttribute(node, name, newValue); setAttribute(node, name, newValue);
} }
}; };
this._templateView._addBinding(binding); this._addBinding(binding);
binding(); binding();
} }
@ -184,7 +200,7 @@ class TemplateBuilder {
} }
}; };
this._templateView._addBinding(binding); this._addBinding(binding);
return node; return node;
} }
@ -240,7 +256,7 @@ class TemplateBuilder {
node = newNode; node = newNode;
} }
}; };
this._templateView._addBinding(binding); this._addBinding(binding);
return node; return node;
} }