Polymer:如何监视<content>属性的变化

tsc*_*hie 5 javascript html5 web-component content-tag polymer

我刚刚开始学习聚合物.这是我的聚合物元素的通用版本:

<polymer-element name="my-element">
    <template>
        <style>
        :host {
            position:absolute;
            width: 200px;
            height: 100px;
            background-color: green;
        }
        </style>
        <p>my element</p>
        <content id="first-in"></content>
        <content id="second-in"></content>
    </template>
    <script>
    Polymer('my-element', {
        domReady: function() {
            alert(this.children[0].getAttribute('title')); 
            //this returns the value I want to observe
        }
    });
    </script>
<polymer-element>
Run Code Online (Sandbox Code Playgroud)

内容标记都填充了另一个自定义元素(再次略微简化):

<polymer-element name="in-element" attributes="title">
    <template>
        <style>
        ...
        </style>
        <p>{{title}}</p>
    </template>
    <script>
    Polymer('in-element', {
        title: 'me'
    });
    </script>
<polymer-element>
Run Code Online (Sandbox Code Playgroud)

我希望能够做的是当(任何)元素(放入内容标记中)中的title属性发生更改时(通过单击事件或其他任何内容)调用my元素中的函数.我不知道如何使用观察或如果我需要使用mutationObserver等来访问它.如何完成/是否可能?

ebi*_*del 8

titlePolymer的数据绑定系统(例如Object.observe()[ info ])无法观察到本机属性.避免它们通常是个好主意.

在你的榜样,我已经改变了titlemytitle与发布了它reflect: true这样的属性值反射回的属性.这样你就可以完全避免.getAttribute()并只检查.mytitle元素.您也可以{{mytitle}}在绑定中使用.

你可以通过变异观察者[ 1 ] 来做到这一点.Polymer提供onMutation监视子项,但您希望监视子项的属性.为此,你需要一个纯MO:

ready: function() {
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(m) {
      if (m.target.localName == 'in-element') { // only care about in-element
        console.log(m.attributeName, m.oldValue, m.target.mytitle);
      }
    });  
  });
  // Observe attribute changes to child elements
  observer.observe(this, {
    attributes: true,
    subtree: true,
    attributeOldValue: true
  }); 
}
Run Code Online (Sandbox Code Playgroud)

演示:http://jsbin.com/doxafewo/1/edit

domReady(),我也改变了你的警觉this.children[0]this.$.firstin.getDistributedNodes()[0].mytitle.使用getDistributedNodes()更好是因为您可以保证实际通过<content>插入点的节点[ 2 ].