What is the point of the “is” syntax when extending elements in web components?

后端 未结 1 944
终归单人心
终归单人心 2020-12-05 19:30

In web components, to register an element you simply type:

var XFoo = document.registerElement(\'x-foo\', {
  prototype: Object.create(HTMLElement.prototype)         


        
1条回答
  •  星月不相逢
    2020-12-05 20:04

    Answer 1 The apparent duplication is because your example is very simple. In the real virtual life, you would provide a different prototype to registerElement.

    Example with a custom button that will display a popup when clicked:

    //Custom method
    function callback ()
    {
        console.log( this + " {created}" )
        this.onclick = function ( event )
        {
            alert( this.id + " " + this.value )
        } 
    }
    
    //Type Extension
    var newProto = Object.create( HTMLButtonElement.prototype )
    newProto.createdCallback = callback
    var XFooButtonExt = document.registerElement( 'x-foo-button', {
        prototype: newProto,
        extends: 'button'
    } )
    

    newProto is different than HTMLButtonElement's prototype.

    With the following HTML code:

    
    

    A click on it will display "Hello World" in a popup.


    Answer 2 The extends: 'button' is a semantic indication that tells the browser that the new prototype provided implements the HTMLButtonElement interface. That's why it's easier to start with an object that inherits from HTMLButtonElement. Instead you could start with an HTMLFormElement prototype but you would have to reimplement all the properties and methods of the HTMLButtonElement interface.

    If not, the element behaviour will be incorrect. In the above example, if you replace a line by:

    var newProto = Object.create( HTMLFormElement.prototype )
    

    ... the click on it will fail because the property value is not implemented in a

    element.

    The property id is always correct because it is provided by the HTMLElement interface, implemented by every elements (including ).

    Note that you could add the missing properties, and link them to their attribute in the attributeChangedCallback method.


    Answer 3 You are correct. This maintains backward compatibility with old browsers that will ignore the second argument, still being able to create a normal element (a standard

    Custom Tag

    Custom Tag

0 讨论(0)
提交回复
热议问题