@livelybone/simple-observer
v4.2.1
Published
A simple implement of observer model and publish-subscribe model
Downloads
28
Maintainers
Readme
@livelybone/simple-observer
pkg.module supported
, which means that you can apply tree-shaking in you project
A simple implement of observer model and publish-subscribe model
repository
https://github.com/livelybone/simple-observer.git
Installation
npm i -S @livelybone/simple-observer
Global name
SimpleObserver
Usage
Observer model
import { Subject, Observer } from '@livleybone/simple-observer'
const subject = new Subject()
const observer = new Observer((...args) => console.log(...args))
// Method -> addObserver
subject.addObserver(observer)
// Method -> notify
// Notify the observers with data
subject.notify(1) // -> console: 1
subject.notify(1, 2) // -> console: 1 2
// Method -> getObserversCount
// Get the number of observers
subject.getObserversCount() // -> 1
// Method -> removeObserver
subject.removeObserver(observer)
Publish-Subscribe model
import { PublishSubscribe } from '@livleybone/simple-observer'
const pubSub = new PublishSubscribe()
// Method -> subscribe
// Subscribe the data provided by publisher
const subscriber = (...args) => console.log(...args)
const subscriberId = pubSub.subscribe(subscriber)
// Method -> publish
// Publish data
pubSub.publish(1) // -> console: 1
pubSub.publish(1, 2) // -> console: 1 2
// Method -> getSubscribersCount
// Get the number of subscribers
pubSub.getSubscribersCount() // -> 1
// Method -> unsubscribe
// Unsubscribe the subscriber via id or callback function of subscriber
pubSub.unsubscribe(subscriberId)
// or pubSub.unsubscribe(subscriber)