Is imperative Mustache-Binding in Polymer.dart sup

2019-04-16 15:25发布

问题:

imperatively i am not able to get a mustache-binding to work in a polymer.dart component:

...
@observable String data = "testData";
...
ready() {
  Element container = this.shadowRoot.querySelector("#container");    
  DocumentFragment newFragement = this.createFragment("<sample-element myAttribute='{{data}}'></sample-element>");
  container.nodes.add(newFragement);
}

the mustache binding is not interpreted, a workaround i found is this one, but i dont know if this is the preferred way to do it and the downside is that i cannot use the mustache-binding imperatively than:

Element newElement = new Element.tag("sample-element");
nodeBind(newElement).bind("myAttribute", new PathObserver(this, "data"));
container.nodes.add(newElement);

Any thoughts welcome! :-)

回答1:

New

Polymer.dart has injectBoundHtml() since a while

<div id="container"></div>

...

this.injectBoundHtml('<foo-bar baz="{{qux}}"></foo-bar>', this.$['container']);

see also https://stackoverflow.com/a/25982843/217408

Original

Justin Fagnani provided a workaround https://groups.google.com/a/dartlang.org/d/msg/web/DYD1NA-SH0A/h-hSU3J8nDYJ

See also this issue https://code.google.com/p/dart/issues/detail?id=19875

Yeah, the problem is that all these bindings and PathObservers are actually reflective. We use smoke as a library that implements the reflective API. When you run in Dartium, this API is implemented with dart:mirrors, but when you build the app with the polymer transformers, we replace the use of mirrors with generated code to help dart2js optimize your app.

To generate the code we need, the polymer transformers parse your app and discover every expression in a template, among other things. Expressions within Dart code, like your example above, are not discovered so we don't know how to generate code for them. That's basically why there is no entry for #commands or #save.

In the future I'd like to add the option of adding your own transformer phase that tells smoke to generate some extra symbols and such, but this is not available today.

Meanwhile, the best way to work around this issue is to make sure those symbols are mentioned in your HTML templates somewhere. It should be enough to define a polymer-element element whose template uses those symbols (even if the element is not used anywhere).



回答2:

i found another way, while doing this.createFragment() i can wrap the HTML with a template-tag and do the templateBind() on this element. Now the Mustache-Binding is interpreted also on imperatively created HTML nodes. ;)

Best Regards, Hilmar