Simple and tiny Observer design pattern implementation written in ES6.
This package is part of quark
framework but it can be used independently.
npm install quark-signal --save
Basic example using add()
and dispatch()
methods.
import Signal from 'quark-signal'
const mySignal = new Signal()
mySignal.add(data => { console.log(data) })
mySignal.dispatch('foo')
Add a signal listener that will be called only once.
import Signal from 'quark-signal'
const mySignal = new Signal()
mySignal.once(data => { console.log(data) })
mySignal.dispatch('foo')
// It will not be dispatched again
mySignal.dispatch('foo')
Priorise a listener so that it will be called first when a signal is dispatched. Higher priority listener will be called earlier.
import Signal from 'quark-signal'
const mySignal = new Signal()
mySignal.add(data => { console.log(data) })
mySignal.add(data => { console.log(data) }, { priority: 1 }) // It will be called first
mySignal.dispatch('foo')
Bind a signal listener with a specific context.
import Signal from 'quark-signal'
const obj = {
foo: 'bar'
}
function callback () {
console.log(this.foo) // = 'bar'
}
const mySignal = new Signal()
mySignal.add(callback, { context: obj })
mySignal.dispatch()
Stop the propagation of a dispatched signal by returning false
in a listener.
import Signal from 'quark-signal'
const mySignal = new Signal()
mySignal.add(() => false)
mySignal.add(data => { console.log(data) }) // It will not be called
mySignal.dispatch('foo')
Check if a signal listener exists.
import Signal from 'quark-signal'
const mySignal = new Signal()
const listener = data => { console.log(data) }
mySignal.add(listener)
const listenerExists = mySignal.has(listener) // = true
Remove a signal listener.
import Signal from 'quark-signal'
const mySignal = new Signal()
const listener = data => { console.log(data) }
mySignal.add(listener)
mySignal.dispatch('foo')
mySignal.remove(listener)
Remove all signal listeners.
import Signal from 'quark-signal'
const mySignal = new Signal()
const listener = data => { console.log(data) }
mySignal.add(listener)
mySignal.add(listener)
mySignal.removeAll()
See https://fm-ph.github.io/quark-signal/
To run the quark-signal
tests, first clone the repository and install its dependencies :
git clone https://github.com/fm_ph/quark-signal.git
cd quark-signal
npm install
Then, run the tests with :
npm test
For coverage, use :
npm test:coverage
- https://github.com/edankwan/min-signal
- https://github.com/millermedeiros/js-signals
- https://github.com/robertpenner/as3-signals
MIT License © Patrick Heng Fabien Motte