How to register a PolymerExpression filter inside a custom element, in Polymer.dart?

StackOverflow https://stackoverflow.com/questions/18936287

  •  29-06-2022
  •  | 
  •  

Pregunta

How do I register a PolymerExpression filter inside a custom element? I am using Polymer.dart.

I want to use this:

<div>Uppercase: {{bob.fullName | uppercase}}</div>

inside the template of my custom element. Where do I register uppercase ?

¿Fue útil?

Solución 2

Inside the PolymerElement, override instanceTemplate:

  DocumentFragment instanceTemplate(Element template) =>
      template.createInstance(this,
          new PolymerExpressions(globals: {
            'uppercase': (String input) => input.toUpperCase()
          }));

Notice you have to create an instance of PolymerExpressions and register the filter. Then you must call template.createInstance

Otros consejos

I tried Seth answer and the expressions themselves are working but somehow I am losing events on my component. My on-click event was not working anymore when I was using:

  DocumentFragment instanceTemplate(Element template) =>
      template.createInstance(this,
          new PolymerExpressions(globals: {
            'uppercase': (String input) => input.toUpperCase()
  }));

I also tried the solution proposed on the polymer expressions page but the binding delegate is apparently missing. Because of a new version maybe?

Anyway, after looking into the code I found another way to have expressions and also to keep events working.

class MyElement extends PolymerElement {

  MainElement.created() : super.created();

  @override
  BindingDelegate syntax = new MyPolymerExpressions();
}

class MyPolymerExpressions extends PolymerExpressions {

  MyPolymerExpressions(): super(globals: {
      'uppercase': (String input) => input.toUpperCase()
  });

  @override
  prepareBinding(String path, name, node) => Polymer.prepareBinding(path, name, node, super.prepareBinding);
}

I noticed that events are working the prepareBinding method is overrided.

If anyone has a better way to do it or some thoughts about this, I am quite interested!

From a discussion on the dart-misc, the polymer expressions is looking for a return that accepts a single argument. So to reproduce the toFixed example of parameters you need to return a function from the filter:

class MyElement extends PolymerElement {

  MainElement.created() : super.created();

  String toFixed(int digits) => (num n) => n.toStringAsFixed(digits);
}

Also, from the polymer_expressions package, you no longer need to do a custom binding/delegate to use the expression filter: "Polymer Expressions are now the default syntax for custom elements." It appears you can just add the function directory to your element and use it as a filter.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top