1
votes

Some method creates new instance of my custom element (created with polymer) and attaches it on page. But I want to check is Element registered before add it and print error to console in bad case. I mean what if I forgot import component html declaration:

<!--I forgot write it in my HTML file -->
<!--<link rel="import" href="packages/visualytik/vis_starter.html">-->

So, in case when I forgot import I want to print error in console.

I know one tricky method:

import 'my_custom_component.dart';
Element component = new Element.tag('my-custom-component');
bool registered = component is MyCustomComponent;

But it's hard method because we should create component first and have to import MyCustomComponent.dart in dart file. Can I check it in other way? Something like:

document.isRegistered('my-custom-component');
1

1 Answers

0
votes

Update3 You can also use the new @HtmlImport annotation. If you import the class, then you can be sure you also have imported the HTML of the element. See also https://stackoverflow.com/a/29710355/217408

Update2 See Hunting down unregistered elements

Update Use a custom constructor in your elements class and do the registration there but only if it wasn't done already.

class MyCustomComponent extends ... {
  bool _isRegistered;
  bool get isRegistered => _isRegistered;
  factory MyCustomComponent() {
    if(!isRegistered) {
      registerElement();
      _isRegistered = true;
    }
    return new Element.tag('my-custom-element');
  }
}

and then create new instances like

new MyCustomElement();

and you can always be sure the element is registered only once (but you always need to use this constructor of course).

Original

If you register your elements by calling document.RegisterElement() yourself instead of relying on Polymer for example, you need to hold a reference to the constructor reference document.RegisterElement() returns, otherwise you won't be able to create an instance of the element. Therefore you just need to check if you already have a reference to the constructor. See also https://developer.mozilla.org/en-US/docs/Web/API/Document/registerElement