PubSub-State
State management inspired by Publish-Subscribe messaging Pattern
Example Projects which have used this library.
NPM Package
- Working on Documentation
- possible to use in umd,cjs,es
import {Pubsub} from 'pubsub-state'
// When there is predefined state data
const predefinedData =
{
userInputs: {
w: 1500,
d: [0, 230,],
},
chartEvent: {
lastIdx: -1,
selectedIdx: {start: -1, end: -1}
}
}
const store = Pubsub(predefinedData)
// When there is no initial data
const store = Pubsub()
store.publish(topic, object data)
- It creates new topic when there's no applicable topic in the store
store.publish('chartData', {dataLength:10})
- If there's an existing topic in the store, it applies to it
store.publish('chartEvent', {lastIdx:5})
store.subscribe(topic, function)
- Register subscriber function to a specific Topic
Subscriber functions will be called when
store.action
is executed.
store.subscribe('chartEvent', (data) => console.log(data))
store.subscribe('chartEvent', (data) => console.log(data.lastIdx + 1))
chartEvent: {
lastIdx: -1,
selectedIdx: {start: -1, end: -1},
sub:[
(data) => console.log(data),
(data) => console.log(data.lastIdx + 1),
}
store.action(topic, anonym function with topic's data arguments)
- It mutates the target topic's data and executes all subscribers passing the topic's data as arguments
-
store.action
's second argument (anonym function)' parameter is the topic's data. You need to return corresponding data object to mutate the topic's data.
store.action('chartEvent', ({lastIdx}) => {
const tempIdx = lastIdx > 0 ? 10 : 2
return ({lastIdx:tempIdx, selectedIdx:{end:tempIdx})
})
- Then it executes all target topic's subscribers
chartEvent: {
lastIdx: 2,
selectedIdx: {start: -1, end: 2},
sub:[
(data) => console.log(data), //1
(data) => console.log(data.lastIdx + 1),//2
}
// 1 >{
lastIdx: 2,
selectedIdx: {start: -1, end: 2
}
// 2 >3