1.0.3 • Published 3 years ago

ember-lifecycle-utils v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

ember-lifecycle-utils

Utils to reduce boilerplate when working with lifecycles

Installation

ember install ember-lifecycle-utils

Usage

Vanilla Classes and Destroyables

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, 'click', this.handleClick);

    return () => {
      window.removeEventListener(eventName, 'click', this.handleClick);
    }
  });
}

So now the above example would be:

class Hello {
  constructor() {
    useWindowEvent(this, 'click', this.handleClick);
    useWindowEvent(this, 'mouseenter', this.handleClick);
  }
}

Modifiers

import { eventListeners } from 'ember-lifecycle-utils/modifier';


export default class Hello extends Component {
  registerListeners = modifier((element) => {
    return eventListeners(element.parentElement,
      ['click', this.onClick],
      ['mouseenter', this.onHover],
    );
  });

  // or shorthand
  registerListeners = modifier(eventListeners(
    ['click', this.onClick],
    ['mouseenter', this.onHover],
  ));


  // ...
}
<button {{this.registerListeners}}>click me</button>

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.