Skip to content

Akumzy/js-event

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

js-event

js-event is a simple JavaScript event emitter primarily created for a React project that needed an event bus.

Installation

# With yarn
yarn add @akumzy/js-event

# With npm
npm install @akumzy/js-event

Usage

// utils.ts
import JSEvent from '@akumzy/js-event'
export const eventBus = new JSEvent()
// components/Counter.tsx
import { useEffect, useState } from 'React'
import { eventBus } from '../utils'

export default function Counter(props) {
  const [count, setCount] = useState(0)

  useEffect(() => {
    const onCount = () => {
      setCount((value) => (value += 1))
    }
    eventBus.addEventListener('oncount', onCount)
    return () => {
      eventBus.removeEventListener('oncount', onCount)
    }
  }, [])

  return <div>Count: {count}</div>
}
// index.tsx
import { eventBus } from './utils'
import Counter from  './components/Counter'

export default function App() {
  const onClick = () => {
    eventBus.dispatch('oncount')
    // eventBus.dispatch('oncount', 10000)
  }

  return (
    <div>
      <h1>React App</h1>
      <button onClick={onClick}>Counter</button>
      <Counter/>
    </div>
  )
}

For Node.js apps please use Node standard event package

About

Simple JavaScript event emitter

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published