在Dart中为什么下面的代码(关于MutationObserver)不起作用?

时间:2013-09-21 01:08:03

标签: dom dart dart-webui

我修改了一个Dart聚合物示例来测试MutationObserver。这是行不通的!有什么建议吗?

这是HTML代码:

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

这是Dart代码:

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!!!!!!!!!!!**
}

有关它为什么不起作用的任何想法?

[注意:网页显示很好,问题只是关于MutationObserver]

谢谢!

2 个答案:

答案 0 :(得分:3)

我认为你不想听#tmpl,而是听它的parentNode。在设置模型时,HTML Template元素将其内容扩展为兄弟姐妹。试试这个改变:

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

答案 1 :(得分:0)

突变观察者事件似乎不能越过阴影边界。

如果将<template>放入自定义元素,则变异观察器将起作用。

以下是一个例子:

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

自定义元素:

<!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>

主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>