I am trying to add attributes in my custom elements and use it within my new element, but having a hard time with the syntax. I have seen this article, but not really clear on it's usage. How can I declare and use the custom "label" attribute in my created callback to render it?

<current-date foo="Today is: "></current-date>

<script>
  document.registerElement('current-date', {
    prototype: {
      createdCallback: function() {
        this.innerHTML = this.foo + new Date();
      },
      foo: {
        value: function() {
          alert('foo() called');
        }
      }
    }
  });
</script>

http://jsbin.com/UdOwizU/4/ (only works in Google Canary)

有帮助吗?

解决方案

Maybe something like this:

<body>
  <current-date label="Today is: "></current-date>

  <script>
    document.registerElement('current-date', {
      prototype: {
        createdCallback: function() {
          this.foo = {value: function() {
            return this.attributes.getNamedItem("label").value;
          }},
          this.innerHTML = this.foo.value.call(this) + new Date();
        }
      }
    });
  </script>
</body>

http://jsbin.com/ivaWUyAL/3/edit

其他提示

What you're probably looking for is the attributeChangedCallback, it will give you a chance to run user code whenever an attribute is set, removed, or modified --> http://w3c.github.io/webcomponents/spec/custom/#types-of-callbacks

Maybe I get you wrong, but have you tried using setAttribute()?

I also can't try registerElement, but it works the "usual" way:

var el = document.createElement( 'current-date' );
el.setAttribute( 'label', new Date() );
document.body.appendChild( el );

In your case this should be something like:

createdCallback: function() {
    this.innerHTML = this.foo + new Date();
    this.setAttribute( 'label', this.getAttribute( 'label' ) + new Date() );
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top