How to create new instance of an extended class of custom elements

前端 未结 2 1218
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 12:51

I\'m trying the example from google developer site and I\'m getting Error: \"TypeError: Illegal constructor. What\'s wrong and How to fix it?

class FancyButt         


        
2条回答
  •  半阙折子戏
    2020-11-30 13:33

    class F_BTN extends HTMLButtonElement{
        constructor(){
            super(); // must call constructor from parent class
            this.addEventListener(...);
            .... // etc.
         }
    }
    
    customElements.define("f-btn",F_BTN,{extends:'button'});
    

    use inline:

      ....  BTN_NAME  ...  
    

    or create append from javascript

    var elm = new F_BTN(...options); 
    // F_BTN = customElements.get('f-btn') // in case F_BTN is out of scope
    

    The problem is elm = document.createElement('f-btn') doesn't work.

    That is why I made my custom create_element function _E

    _E = function (name, html) {
      var $;
      switch (true) {
        case (name === '' || !name):  // _E()  -- a div
            {
                $ = document.createElement('div');
            }
            break; 
        case (!name.indexOf('<')):  // _E('

    abcA

    ') -- sub_dom { $ = document.createElement('div'); $.innerHTML = name; $ = $.firstElementChild; } break; default: var c = window.customElements.get(name); if(c){ $ = new c(); // _E('f-btn') -- customElement } else { $ = document.createElement(name); // _E('button') -- htmlElement } } if (html) $.innerHTML = html; return $; }; var elm1 = _E('f-btn'); parent.appendChild(elm1);

提交回复
热议问题