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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With