In Dart why the code below (about MutationObserver) dose not work?

不羁的心 提交于 2019-11-29 08:47:49

I think you don't want to listen on #tmpl, but on its parentNode. HTML Template element expands its contents as siblings when a model is set. Try this change:

observer.observe(query('#tmpl').parent, childList: true, subtree: true); 

It doesn't appear that mutation observer events can cross the shadow boundary.

If you put the <template> into a custom element, the mutation observers will work.

Here is an example:

import 'package:polymer/polymer.dart';
import 'dart:html';
import 'dart:async';

@CustomTag("my-element")
class MyElement extends PolymerElement with ObservableMixin {
  final List<String> timestamps = toObservable([]);
  MutationObserver observer;

  created() {
    super.created();

    observer = new MutationObserver(_onMutation);
    observer.observe(getShadowRoot('my-element').query('#timestamps'), childList: true, subtree: true);

    new Timer.periodic(const Duration(seconds: 1), (t) {
      timestamps.add(new DateTime.now().toString());
    });
  }

  // Bindings, like repeat, happen asynchronously. To be notified
  // when the shadow root's tree is modified, use a MutationObserver.

  _onMutation(List<MutationRecord> mutations, MutationObserver observer) {
    print('${mutations.length} mutations occurred, the first to ${mutations[0].target}');
  }
}

The custom element:

<!DOCTYPE html>

<polymer-element name="my-element">
  <template>
    <ul id="timestamps">
      <template repeat="{{ts in timestamps}}">
        <li>{{ts}}</li>
      </template>
    </ul>
  </template>
  <script type="application/dart" src="my_element.dart"></script>
</polymer-element>

The main HTML:

<!DOCTYPE html>

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

  <body>
    <my-element></my-element>
  </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!