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

前端 未结 2 1593
盖世英雄少女心
盖世英雄少女心 2020-12-18 16:07

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

This is the HTML code:

   
相关标签:
2条回答
  • 2020-12-18 16:47

    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); 
    
    0 讨论(0)
  • 2020-12-18 16:53

    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>
    
    0 讨论(0)
提交回复
热议问题