问题
I created a WebComponent where I created a constructor for it. When run, this constructor does not seem to be invoked, though the rest of the components work, but they have to be created outside my custom constructor. Here is an example of what I'm talking about.
<element name="x-navigation" constructor="Navigation" extends="div">
<template>
<div>{{items}}</div>
</template>
<script type="application/dart">
import 'package:web_ui/web_ui.dart';
class Navigation extends WebComponent {
List<String> items = new List<String>();
Navigation() {
items.add("Hello");
}
}
</script>
<element>
If I include this component, the output will be an empty list, as if the constructor I created has not been called. There should be at least the "Hello" string output, but it isn't. Are constructors created this way ignored, or have I missed something?
回答1:
The latest version of Web UI now calls the constructor, and there is also the created
lifecycle method available for you.
The following code is adding both hello's:
<element name="x-navigation" constructor="Navigation" extends="div">
<template>
<div>{{items}}</div>
</template>
<script type="application/dart">
import 'package:web_ui/web_ui.dart';
class Navigation extends WebComponent {
List<String> items = new List<String>();
Navigation() {
items.add("Hello first");
}
created() {
items.add("Hello second");
}
}
</script>
<element>
I recommend reading the article on lifecycle methods: http://www.dartlang.org/articles/dart-web-components/spec.html#lifecycle-methods
Lifecycle methods
created() - Invoked slightly after a component is created.
inserted() - Invoked whenever a component is added to the DOM.
attributeChanged() - Invoked whenever an attribute in the component changes.
removed() - Invoked whenever a component is removed from the DOM
回答2:
Add following method in class:
created() {
items.add("Hello");
}
来源:https://stackoverflow.com/questions/13947748/how-do-i-get-webcomponent-classes-to-invoke-my-custom-constructor