modum
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

Modum

A utility for logically grouping the performance and destruction of side effects. Inspired by React's useEffect hook.

Why the name you ask? Modum is Latin for effect.

Problem

Most JavaScript frameworks have some type of "init" and "destroy" life cycle functions. For example, React has componentDidMount() and componentWillUnmount(); and similarly Angular has ngOnInit() and ngOnDestroy().

The problem with these functions is that often times the work that you have to do on "init" closely mirrors the work that you have to do on "destroy". So you end up with this highly coupled code split between two different functions.

Modum addresses that problem by letting you declare both the "init" and "destroy" logic at the same time in the same place. It's just not all run at the same time. The function that you pass to perform() (the effect) is run immediately, and the function that you return from the effect is not run until you tell Modum to destroy that side effect.

Example usage

import Modum from 'modum'

let modum = new Modum()

modum.perform(() => {
  console.log('Side effect 1 performed')
  return () => console.log('Side effect 1 cleaned up!')
})

modum.perform(() => {
  console.log('Side effect 2 performed')
  return () => console.log('Side effect 2 cleaned up!')
})

modum.destroyAll()

API

perform(effect)

Perform a side effect. You can optionally return a function from the effect that cleans up the effect. This ensures that these highly related functions are logically grouped in your code.

destroy(id)

Clean up a particular side effect that has been performed.

let modum = new Modum()

let id = modum.perform(() => {
  console.log('Side effect 1 performed')
  return () => console.log('Side effect 1 cleaned up!')
})

modum.destroy(id)

destroyAll()

Clean up all side effects that have been performed since the last time this function was called.

addEvent(el, eventType, handler, options)

Perform the specific effect of adding an event listener to an element. This event is then automatically removed when the side effect is destroyed.

Argument name Type Description
element Element The element to add the event listener to
eventType string The type of event to add
handler EventListenerOrEventListenerObject The event handler
options boolean | EventListenerOptions Optional. These options get passed directly through to the addEventListener function.

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 0.0.1
    0
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 0.0.1
    0

Package Sidebar

Install

npm i modum

Weekly Downloads

0

Version

0.0.1

License

MIT

Unpacked Size

8.04 kB

Total Files

6

Last publish

Collaborators

  • zposten
  • olivare