I am trying to using the custom elements spec to extend native DOM elements using the "is" attribute, but it doesn't seem to be doing anything at all. I am using Google Canary so I am able to create custom elements, but no effect in extending.

In my sample, I am trying to add a caption to the native img tag:

<img is="super-img" src="http://lorempixel.com/400/200/" 
  caption="This is my custom caption!" />

<script>
  document.registerElement('super-img', {
    prototype: Object.create(HTMLImageElement.prototype, {
      createdCallback: function() {
        var caption = this.attributes.getNamedItem('caption').value;
        alert(caption);
      }
    })
  });
</script>

http://jsbin.com/OMaPIVoV/3/

The createdCallback never fires. Any ideas on how to accomplish this?

有帮助吗?

解决方案 2

looks like you forgot to tell your web component, that it extends the native img element. Here's a running example based on your fiddle but broken down to the important bits: http://jsbin.com/OMaPIVoV/7/edit

hope this helps!

其他提示

Object.create(HTMLImageElement.prototype, {
    createdCallback: function() {…}
})

Object.create does create a map of property descriptors as its second parameter - not plain values - like Object.defineProperties does.

This is also mentioned in the article you found at "Adding JS properties and methods":

Of course there are umpteen thousand ways to construct a prototype. If you're not a fan of creating prototypes like this, here's a more condensed version of the same thing:

[…] [This] first format allows for the use of ES5 Object.defineProperty. The second allows the use of get/set.

(The strike-through was added by me as it's rubbish)

So what you want is either

var SuperImgProto = Object.create(HTMLImageElement.prototype);
SuperImgProto.createdCallback = function() { … };
var SuperImg = document.registerElement('super-img', {prototype: SuperImgProto});

or

document.registerElement('super-img', {
  prototype: Object.create(HTMLImageElement.prototype, {
    createdCallback: {value: function() { … } }
  })
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top