Jan 3, 2017

Custom Element

Custom element give power of defining your own custom element which can be used as native html element. You can also extend existing native HTML element, which can add more features to it, based on your requirement.

Currently most of the web pages looks like this, this may not be easy to understand/maintain as div is just a generic container and which does not indicate about the item which it contains.

<div>
<div>
<div></div>
<div></div>
</div>
</div>

With the use of custom element you can transform it like this. By element's name itself its clear what it contains.

<product-item>
<product-review>
<user-avatar></user-avatar>
<user-comment></user-comment>
</product-review>
</product-item>

Registering and utilizing a custom element

  • Define a prototype for the custom element

                 var MyElementPrototype = Object.create(HTMLElement.prototype);

                 var MyButtonPrototype = Object.create(HTMLButtonElement.prototype);


  • Add callback function in which you create element


               MyElementPrototype.createdCallback = function(){
                              this.innerHTML = "<h2>My Element</h2>";
                       }

              MyButtonPrototype.createdCallback = function(){
     this.style.color='red';
     this.innerHTML = "test";
      }

  • Register the element

             var MyElement = document.registerElement('my-element',{
                                   prototype:MyElementPrototype
                     });

             var MyButtonPrototype = document.registerElement('my-button',{
                                  prototype:MyButtonPrototype,
                  extends: 'button'
     });

Instantiate Custom element

  • Markup

 <my-element/>


  • new operator

    var myElement = new MyElement();
    document.getElementById('someid').innerHTML = '<my-element/>'


  • create element

     var myElement = document.createElement('my-element');
     document.getElementById('someid').appendChild(myElement);


  • Inner HTMLElement

     document.getElementById('someid').innerHTML = '<my-element/>'

Life cycle callback

  • createdCallback - Instance is created
  • attachedCallback - Instance inserted to DOM
  • detachedCallback - Instance detached from DOM
  • attributeChangedCallback - Any attribute update

No comments:

Post a Comment