简体   繁体   中英

How do you create custom Polymer and PolymerDart annotations?

I was doing some research into PolymerDart and the various annotations which can be applied to the dart files. Be it: @Property , @property , @observe , @reflectable , @PolymerRegister , OR @HtmlImport .

So, I started to look into the concept of Dart and how to make annotations for them. I saw on stackoverflow that you can do something like this.

class Datatable {
  final String name;
  const DataTable(this.name);
}

which can easily do some additional information inside the constructor optionally.

class Datatable {
  final String name;
  const DataTable(this.name) {
    console.log("$name was referenced.");
  }
}

So, I can create and implement a variety of Annotations we could leverage, but this is where it starts to get fishy.

I was curious if there was a way to create annotations for polymerdart? is that mostly locked down, or can is there a way to create ones which do simple functions, maybe even for example: creating an Annotation which executes the @Property(computed:"") functionality.

I was wanted to create some sort of customization for our team to use.

For the record, I know that i can do something like

const myCustomAnnotation = const Property();

which would allow me to do:

@myCustomAnnotation

I was thinking I could then do something like like:

class myCustomComputed extends Property {
  final String functionName;
  const myCustomComputed() : Property(computed: this.functionName);
}

to allow me to do something like:

@myCustomComputed("testFunction(varA)")

This is a big topic, but the brief answer is, yes, what you describe is technically possible but not trivial.

Dart annotations are available at runtime via reflection, but are most often used by pub transformers during the build process. The purpose of a transformer is to modify assets (eg dart code) to some new form before runtime.

The Polymer annotations you mentioned above are handled by the Polymer transformer . This transformer handles identifying the annotations you mentioned above and automatically rewriting annotated code to include all the necessary implementations and wiring such that everything behaves as we expect as Polymer elements.

So there's nothing stopping you from defining your own annotations and transformers, including those that build upon the existing Polymer transformers, and packaging it up for your own or others' use.

I will note though that it is somewhat complex topic (ref the Polymer transformer) and there seem to be few simple code-rewriting transformer examples from which to build on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM