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

若如初见. 提交于 2019-11-28 02:18:09

问题


I modified one the Dart polymer example to test MutationObserver. It does not work! Any suggestion?

This is the HTML code:

<body>   
<ul>      
  <template id="tmpl" repeat>
    <li>{{}}</li>
  </template>
</ul>
</body>

This is Dart code:

MutationObserver observer = new MutationObserver(_onMutation);
observer.observe(query('#tmpl'), childList: true, subtree: true); 
List timestamps = toObservable([]); 
query('#tmpl').model = timestamps;

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

_onMutation(List<MutationRecord> mutations, MutationObserver observer) {
 print('hello test MutationObserver');  **//there is not any print!!!!!!!!!!!**
}

Any idea about why it would not work?

[Note: The webpage display is fine, problem is just about the MutationObserver]

Thanks!


回答1:


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); 



回答2:


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>


来源:https://stackoverflow.com/questions/18927901/in-dart-why-the-code-below-about-mutationobserver-dose-not-work

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