Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla Web Component custom event attributes and properties

Using Web Components without any framework, what is the proper way to implement a custom event? For example, say I have a custom element x-pop-out that has a custom event of pop I would want all of the following to work:

<x-pop-out onpop="someGlobal.doSomething()"/>

var el = document.getElementsByTagName('x-pop-out')[0];
el.onpop = ()=> someGlobal.doSomething();
//or
el.addEventListener('pop', ()=> someGlobal.doSomething());

The last one I get how to do, but do I need to custom implement the attribute and a getter / setter for each? Also, is eval() the appropriate way to execute the string from the attribute?

like image 262
hapticdata Avatar asked Feb 18 '17 22:02

hapticdata


2 Answers

The event listener solution (the third one) is the easiest because you don't have to define anything special to catch the event.

The event handler solutions need to make an eval() (first one, from attribute) or to call the fonction explicitely (second one).

If you can't use eval you can instead parse the attribute string.

customElements.define( 'x-pop-out', class extends HTMLElement {
    connectedCallback() {
        this.innerHTML = `<button id="Btn">pop</button>`

        this.querySelector( 'button' ).onclick = () => {
            this.dispatchEvent( new CustomEvent( 'pop' ) )
            if ( this.onpop )
                this.onpop()
            else
                eval( this.getAttribute( 'onpop' ) )
        }            
    }
} )

XPO.addEventListener( 'pop', () => console.info( 'pop' ) )
<x-pop-out id=XPO onpop="console.log( 'onpop attribute' )"></x-pop-out>
<hr>
<button onclick="XPO.onpop = () => console.log( 'onpop override' )">redefine onpop</button>
like image 172
Supersharp Avatar answered Oct 17 '22 07:10

Supersharp


Based on SuperSharp answer. His suggestion would only work for console logs and not actually the events. The solution I used was to override dispatchEvent and made it to also create custom HTML event attributes.

Following the standard of using 'on' + event.type. We mask the attribute in a new function using with and check if the attribute is a function and pass in the event if required.

dispatchEvent(event) {
  super.dispatchEvent(event);
  const eventFire = this['on' + event.type];
  if ( eventFire ) {
    eventFire(event);
  } else {
  const func = new Function('e',
    'with(document) {'
       + 'with(this) {'
         + 'let attr = ' + this.getAttribute('on' + event.type) +';'
         + 'if(typeof attr === \'function\') { attr(e)};
       + }'
     + '}'
   );
   func.call(this, event);
   } 
}

Example:

class UserCard extends HTMLElement {

  constructor() {
    // If you define a constructor, always call super() first as it is required by the CE spec.

    super(); //

  }


  dispatchEvent(event) {
    super.dispatchEvent(event);

    const eventFire = this['on' + event.type];
    if (eventFire) {
      eventFire(event);
    } else {
      const func = new Function('e',

        'with(document) {' +
        'with(this) {' +
        'let attr = ' + this.getAttribute('on' + event.type) + ';' +
        'if(typeof attr === \'function\') { attr(e)};' +
        '}' +
        '}');
      func.call(this, event);
    }

  }

  connectedCallback() {
    this.innerHTML = `<label>User Name</label> <input type="text" id="userName"/>
   <label>Password</label> <input type="password" id="passWord"/>
    <span id="login">login</span>`;
    this.test = this.querySelector("#login");
    this.test.addEventListener("click", (event) => {
      this.dispatchEvent(
        new CustomEvent('pop', {
          detail: {
            username: 'hardcodeduser',
            password: 'hardcodedpass'
          }
        })
      );
    })


  }

}

customElements.define('user-card', UserCard);

function onPop2(event) {
  debugger;
  console.log('from function');
}
<user-card id="XPO" onpop="onPop2"></user-card>
<hr>
<user-card id="XPO" onpop="console.log('direct Console')"></user-card>
like image 3
Jordan Hall Avatar answered Oct 17 '22 07:10

Jordan Hall