Skip to content

NullVoxPopuli/ember-lifecycle-utils

main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

ember-lifecycle-utils

npm version CI

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.