1

我修改了一个 Dart 聚合物示例来测试 MutationObserver。这没用!有什么建议吗?

这是 HTML 代码:

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

这是飞镖代码:

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]

谢谢!

4

2 回答 2

3

我认为您不想在#tmpl 上收听,而是在其 parentNode 上收听。设置模型时,HTML 模板元素将其内容扩展为同级。试试这个改变:

observer.observe(query('#tmpl').parent, childList: true, subtree: true); 
于 2013-09-21T01:26:08.943 回答
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>
于 2013-09-21T01:28:24.777 回答