kkkk
Allow related code to live in the same place.
didInsertElement() {
this.element
.querySelector('button')
.addEventListener('click', this.handleClick);
}
class HelloWorld extends Component {
addTooltipListener() {
// save the element so we can remove the listener later
this._tooltip = this.element.querySelector('.tooltip');
if (this._tooltip) {
this._tooltip.addEventListener(
'mouseover',
this.toggleTooltip
);
}
}
removeTooltipListener() {
if (this._tooltip) {
this._tooltip.removeEventListener(
'mouseover',
this.toggleTooltip
);
}
}
didInsertElement() {
this.element
.querySelector('button')
.addEventListener('click', this.handleClick);
this.addTooltipListener();
}
didUpdate() {
this.removeTooltipListener();
this.addTooltipListener();
}
willDestroyElement() {
this.element
.querySelector('button')
.removeEventListener('click', this.handleClick);
this.removeTooltipListener();
}
// ...
}
<div {{action this.handleClick}}></div>
<div onclick={{action this.handleClick}}></div>
<!-- MODIFIER -->
<div {{action this.handleClick}}></div>
<!-- HELPER -->
<div onclick={{action this.handleClick}}></div>
export default class DarkMode extends Modifier {
@service userSettings;
didInsert(element, [darkModeClass]) {
if (this.userSettings.darkModeEnabled) {
this._previousDarkModeClass = darkModeClass;
element.classList.add(darkModeClass);
}
}
willDestroy(element) {
element.classList.remove(this._previousDarkModeClass);
}
didUpdate() {
this.willDestroy(...arguments);
this.didInsert(...arguments);
}
}
<!-- usage -->
<div {{dark-mode 'ui-dark'}}></div>
function darkMode(userSettings, element, [darkModeClass]) {
if (userSettings.darkModeEnabled) {
element.classList.add(darkModeClass);
return () => {
element.classList.remove(darkModeClass);
};
}
}
export default modifier(
{ services: ['userSettings'] },
darkMode
);
@modifier
function darkMode(
@service userSettings,
element,
[darkModeClass]
) {
if (userSettings.darkModeEnabled) {
element.classList.add(darkModeClass);
return () => {
element.classList.remove(darkModeClass);
}
}
}