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

霸气de小男生 提交于 2019-11-29 14:09:49

Native properties like title are not observable by Polymer's data-binding system (e.g. Object.observe() [info]). It's generally a good idea to avoid them.

In your example, I've changed title to mytitle and published it with reflect: true so the property value reflects back to the attribute. This way you can completely avoid .getAttribute() and just check .mytitle on in-elements. You can also use {{mytitle}} in bindings.

You can do this through mutation observers [1]. Polymer provides onMutation to monitor children but you want to monitor attributes of children. For that, you need a pure 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
  }); 
}

Demo: http://jsbin.com/doxafewo/1/edit

In domReady(), I also changed your alert of this.children[0] to this.$.firstin.getDistributedNodes()[0].mytitle. Using getDistributedNodes() is better because you're guaranteed to have the nodes that are actually passing through the <content> insertion point [2].

For every attribute there is a watcher. So in your case it should be looking like this. Although there are 2 different implementation, one with attribute name as the first argument of the function.

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

Polymer change watchers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!