聚合物:如何关注内容的变化属性

Polymer: How to watch for change in <content> properties

本文关键字:变化 属性 何关注 聚合物      更新时间:2023-09-26

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

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

内容标签都用另一个自定义元素填充(再次稍微简化):

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

我想要能够做的是调用my-element中的函数,当(任何)in-element中的title属性(放在content标签中)被更改时(通过单击事件或其他)。我不确定如何访问这个使用观察或如果我需要使用mutationObserver等。这是怎么做的/可能吗?

title这样的天然性质是聚合物的数据绑定系统无法观察到的(例如Object.observe() [info])。一般来说,避免使用是一个好主意。

在您的示例中,我已将title更改为mytitle并将其与reflect: true一起发布,因此属性值反映回属性。这样你就可以完全避免.getAttribute(),而只检查in-elements上的.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
  }); 
}

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

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

每个属性都有一个观察者。在这种情况下,它应该是这样的。虽然有两种不同的实现,其中一种将属性名作为函数的第一个参数。

Polymer('in-element', {
    title: 'me',
    titleChanged: function(oldVal, newVal) {
        // do something
    }
});

聚合物变化观察者