Utils to reduce boilerplate when working with lifecycles
ember install ember-lifecycle-utils
import { withCleanup } from 'ember-lifecycle-utils';
class Hello {
constructor() {
withCleanup(this, () => {
window.addEventListener('click', this.handleClick);
return () => {
window.removeEventListener('click', this.handleClick);
}
});
}
}
This can be used to help make even more concise helpers, like:
function useWindowEvent(context, eventName, handler) {
withCleanup(context, () => {
window.addEventListener(eventName, lick', this.handleClick);
return () => {
window.removeEventListener(eventName, lick', this.handleClick);
}
});
}
So now the above example would be:
class Hello {
constructor() {
useWindowEvent(this, 'click', this.handleClick);
useWindowEvent(this, 'mouseenter', this.handleClick);
}
}
import { eventListeners } from 'ember-lifecycle-utils/modifier';
export default class Hello extends Component {
registerListeners = modifier((element) => {
return eventListeners(element.parentElement,
['click', this.onClick],
['moustenter', this.onHover],
);
});
// or shorthand
registerListeners = modifier(eventListeners(
['click', this.onClick],
['mouseenter', this.onHover],
));
// ...
}
See the Contributing guide for details.
This project is licensed under the MIT License.