@livelybone/simple-observer

A simple implement of observer model and publish-subscribe model

Stats

stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
10Jul 11, 2019Aug 27, 2018Minified + gzip package size for @livelybone/simple-observer in KB

Readme

@livelybone/simple-observer

NPM Version Download Month gzip with dependencies: 1kb ts pkg.module

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)

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.