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