Question

After overriding three lifecycle methods of WebComponent: created(), inserted(), and removed(), I can see that the first two are called consistently but removed() is never called. Is there anything special that needs to be done so that removed() is called? Or is it simply never called?

Was it helpful?

Solution

The removed() method is called when a custom element is removed from the DOM. Here is a small program that demonstrates the use of the created(), inserted(), and removed() lifecycle events.

Create a Dart web application with an index.html file that looks like this:

<!DOCTYPE html>

<html>
  <head>
    <title>index</title>
    <link rel="import" href="my_element.html">
    <script src="packages/polymer/boot.js"></script>
  </head>

  <body>
    <div id='container'><my-element></my-element></div>
    <script type="application/dart">
      import 'dart:html';
      void main() {
        query('#container').onClick.listen((event) {
          event.target.remove();
        });
      }
    </script>
  </body>
</html>

This file imports and displays a custom element, <my-element>.

Define the following file that defines <my-element>:

<!DOCTYPE html>

<html>
  <body>
    <polymer-element name="my-element">
      <template>
        <p>The name is {{person.name}}</p>
      </template>

      <script type="application/dart" src="my_element.dart"></script>
    </polymer-element>
  </body>
</html>

And define the accompanying Dart file that demonstrates the lifecycle methods getting called:

import 'package:polymer/polymer.dart';

class Person extends Object with ObservableMixin {
  @observable String name;
  Person(this.name);
}

@CustomTag("my-element")
class MyElement extends PolymerElement {
  @observable Person person = new Person('Shailen');

  void created() {
    super.created();
    print('created');
  }

  void inserted() {
    print('inserted');
  }

  void removed() {
    print('removed');
  }
}

When you run index.html, you will see a paragraph with some text in it. The created() and inserted() lifecycle methods are called, and 'created' and 'inserted' messages print in the console. When you click on the div that contains the custom element, the element is removed, the removed() lifecycle method is called, and 'removed' prints in the console.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top