1

基本上我正在设计一个元素,根据它的 s 来说明它<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 在他的一个答案中提到(如果我找到它会发布链接),答案是MutationObservers

如果我不求助于 MutationObservers,Polymer 1.0是否附带任何可以帮助我的东西?

如果不是,那么在这里实现 MutationObserver 的最高效方式是什么?以及元素的哪个生命周期回调?对不起,我对 MutationObserver 完全陌生。

4

1 回答 1

2

除非您的子元素是 Polymer 自定义元素,否则恐怕您必须使用MutationObservers。就像是:

<!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,因为此时默认值和模板元素已经准备好。

于 2015-07-04T09:19:43.760 回答