Skip to content

Commit

Permalink
Add _addEventHandlers() method to MyElement base class
Browse files Browse the repository at this point in the history
  • Loading branch information
nfreear committed Apr 19, 2023
1 parent 7975efe commit df83bfd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
13 changes: 13 additions & 0 deletions src/MyElement.js
Expand Up @@ -156,6 +156,19 @@ export class MyElement extends HTMLElement {

this.channel.addEventListener('message', ev => callbackFn ? callbackFn(ev) : console.debug('Message:', ev));
}

get events () { return []; } // { sel: '#button', name: 'click', fn: '_clickHandler' }

_addEventHandlers () {
this.events.forEach((IT) => {
const ELEM = this.shadowRoot.querySelector(IT.sel);
const METHOD = this[IT.fn];
if (!ELEM || typeof METHOD !== 'function') {
throw new Error(`Add event handlers failed: '${IT.sel}' or '${IT.fn}'`);
}
ELEM.addEventListener(IT.name, (ev) => METHOD.call(this, ev));
});
}
}

export default MyElement;
18 changes: 9 additions & 9 deletions src/components/MyStarRatingElement.js
Expand Up @@ -16,6 +16,13 @@ export class MyStarRatingElement extends MyElement { // HTMLInputElement {
return 'my-star-rating';
}

get events () {
return [
{ sel: 'fieldset', name: 'click', fn: '_clickEventHandler' },
{ sel: 'fieldset', name: 'mouseout', fn: '_unfocusStars' }
];
}

async connectedCallback () {
const name = this.getAttribute('name') || 'my-star-rating-1';

Expand All @@ -26,23 +33,16 @@ export class MyStarRatingElement extends MyElement { // HTMLInputElement {
const templates = await this.getTemplate('my-star-rating');

const labels = this.shadowRoot.querySelectorAll('label');
const fieldset = this.shadowRoot.querySelector('fieldset');

const hiddenInput = this._createHiddenInput(attr.name);

this.after(hiddenInput);

this.$$ = {
...attr, hiddenInput, labels, fieldset, templates
};
this.$$ = { ...attr, hiddenInput, labels, templates };

this._appendStars(labels, templates[1]);

fieldset.addEventListener('click', ev => this._clickEventHandler(ev));
fieldset.addEventListener('mouseout', ev => {
this._unfocusStars();
// console.debug('mouseout');
});
this._addEventHandlers();

console.debug('my-star-rating (radio):', this.$$, this);
}
Expand Down

0 comments on commit df83bfd

Please sign in to comment.