Heruan Heruan - 6 months ago 117
HTML Question

How an Aurelia binding behavior could enhance an innerHTML content?

In my web app I'm using a Markdown value converter to render HTML from a Markdown string, e.g.

<div innerhtml.bind="string | markdown"></div>


This works nice and inside the
div
I get an HTML rendering of the Markdown content in
string
.

The value converter is able to render an Aurelia custom element in the output, but being that element inside the value converter output as a string, it's not enhanced by the Aurelia's templating engine.

Would a binding behavior be able to use the
TemplatingEngine
to enhance the output of the value converter once rendered in the DOM, every time the source value changes? Something like:

<div innerhtml.bind="string | markdown & enhance"></div>


I've tried this, but it doesn't work (it's being evaluated before
target
gets its children):

export class EnhanceBindingBehavior {

private templatingEngine: TemplatingEngine;

public constructor(templatingEngine: TemplatingEngine) {
this.templatingEngine = templatingEngine;
}

public bind(binding: Binding, scope: Scope): void {
let target: HTMLElement = binding["target"];
for (let i = 0; i < target.children.length; i++) {
console.log("enhancing element " + i);
this.enhance(target.children[i]);
}

}

public unbind(binding: Binding, scope: Scope): void {

}

private enhance(element: Element): void {
this.templatingEngine.enhance({
element: element
});
}
}


Would it be possibile at all?

Answer

The binding behavior's bind method is invoked immediately before the binding instance applies the model value to the target element which explains why the div's children don't exist yet- the string | markdown part of the binding expression hasn't been applied yet.

I think an aurelia custom attribute would be a better fit for this use-case. Something like:

<div enhance.bind="myMarkdownString | markdown">

Or even:

<div enhanced-markdown.bind="myMarkdownString">

Either of these would give you better control over the process.

Comments