quark-signal
Simple and tiny Observer design pattern implementation written in ES6.
This package is part of quark
framework but it can be used independently.
Installation
npm install quark-signal --save
Usage
Basic
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 once
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')
Priority
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')
Context
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()
Propagation
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')
Has
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
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()
API
See https://fm-ph.github.io/quark-signal/
Testing
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
References
- https://github.com/edankwan/min-signal
- https://github.com/millermedeiros/js-signals
- https://github.com/robertpenner/as3-signals
License
MIT License © Patrick Heng Fabien Motte