用于添加子节点的聚合事件/回调

Polymer event / callback for adding childNodes

本文关键字:回调 聚合事件 添加 子节点 用于      更新时间:2023-09-26

基本上我在设计一个元素,比如<parent-element>,它根据它的childNode来做的事情。

所以当我做这个

<parent-element>
  <div> </div>
  <child-element> </child-element>
  <paper-button> </paper-button>
</parent-element>

一切都很好。但是,当我想在动态添加新子项时获得事件/回调时,如下所示:

Polymer.dom(document.querySelector('parent-element')).appendChild(document.createElement('p'))

如何获取触发新子项的回调/事件?

我已经尝试了所有的生命周期回调,created, attached, detached, attributeChanged

此外,根据该组件的设计,它可以有任何类型的子级、常规HTML标记、Web组件等。因此,事件必须在我的<parent-element>元素中触发,而不是在它的任何子级中触发。

@ebidel在他的一个答案中提到(如果我找到了,会发布链接(,答案是MutationObservators

Polymer 1.0是否提供了任何可以帮助我而无需求助于MutationObserver的东西?

如果不是,在这里实现MutationObserver的最高效的方法是什么?在元素的哪个生命周期回调中?很抱歉,我对MutationObserver完全陌生。

除非您的子元素是Polymer自定义元素,否则恐怕您必须使用MutationObserver。类似于:

<!DOCTYPE html>
<html>
<head>
  <title>polymer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
  <script src="https://rawgit.com/webcomponents/webcomponentsjs/master/webcomponents-lite.js"></script>
  <link rel="import" href="https://rawgit.com/Polymer/polymer/master/polymer.html">
</head>
<body>
<dom-module id="x-test">
  <template>
    <h1>Mutation Observer Test</h1>
    <button on-tap="addTapped">Add Node</button>
    <button on-tap="removeTapped">Remove Node</button>
    <div id="insertion_point" style="color:red"></div>
    <div id="console_log"></div>
  </template>
</dom-module>
<script>
  HTMLImports.whenReady(function() {
    Polymer({
      is: 'x-test',
      properties: {
        _mo: {type: Object, value: function () {return {};}}
      },
      ready: function () {
        // first, define the mutation observer.
        var t = this;
        this._mo = new MutationObserver(function (mutations) {
          // because mutations are "collected in intervals"
          mutations.forEach(function(mutation) {
            t.consoleLog("node added or removed detected");
            // add in your tasks when node is added/removed here
          });
        });
        // next, start observing.
        this._mo.observe(this.$.insertion_point, {
          // configure `childList` to be true to listen to node addition/deletion
          childList: true
        });
      },
      consoleLog: function (m) {
        var el = document.createElement("div");
        el.innerHTML = m;
        Polymer.dom(this.$.console_log).appendChild(el);
      },
      addTapped: function () {
        var el = document.createElement("span");
        el.innerHTML = "new node!";
        Polymer.dom(this.$.insertion_point).appendChild(el);
      },
      removeTapped: function () {
        var el = Polymer.dom(this.$.insertion_point).lastElementChild;
        Polymer.dom(this.$.insertion_point).removeChild(el);
      }
    });
  });
</script>
<x-test></x-test>

</body>
</html>

Jsbin:http://jsbin.com/huxuloyobi/edit?html,输出

我在ready回调中定义了MO,因为默认值和模板元素已经准备好了。