Collection of promise oriented functions and classes.
Install with npm: npm i -S tarkjs
ES6 imports.
import * as tarkjs from 'tarkjs'
There is no default export.
The EventBus is a custom event dispatcher that process events to handlers in the order they were added asynchronously. The events are cancelable by the handlers and the dispatch, stopping propagation to the next handler. The return value of each handler is kept in an accumulator and the original dispatch will resolve with those values.
import { EventBus, changeNotifier } from 'tarkjs'
const eventBus = new EventBus()
// Create an object that send events when it's properties are set.
const notifier = changeNotifier({message: 'hello'}, eventBus)
// attach an handler
eventBus.addEventHandler('message_value_changed', (e) => {
console.log(e.payload.newValue)
})
// send a value changed event
notifier.message = 'hi'
// Send any event
eventBus.addEventHandler('custom_event', ({event, payload, acc, i, end}) => {
// code...
})
eventBus.dispatch({event: 'custom_event', payload: 'hello'})
// Accumulate
[1, 2, 3].forEach(i => eventBus.addEventHandler('accumulate', () => i))
const { promise } = eventBus.dispatch({event: 'accumulate'})
promise.then(({acc}) => acc.reduce((p,n) => p+n))
Give a regex as event to EventBus#addEventHandler
to handle any events that match the pattern.
- changeNotifier Dispatch events when an object properties are set.
- mutationNotifier Dispatch events on dom-changes.
- webworkerNotifier Dispatch events on web-worker message.
- promiseNotifier Dispatch events on promise resolve or rejection.
Store the result and dispatch events of promise resolve and rejection from promise creator functions.
import { PromiseStore, fetchRequest } from 'tarkjs'
// Actions must return a promise.
const store = new PromiseStore({simple_fetch: (url) => fetchRequest(url)})
// Subscribe get all the events of an action.
store.subscribe('simple_fetch', (e) => {
const { fulfilled } = store.actionStore.simple_fetch.STATES
if (e.event === fulfilled)
console.log(e.payload)
})
// The values are stored in the actionStore
if (!store.actionStore.simple_fetch.store.pending)
store.actions.simple_fetch('some_text.txt')
A web socket that store a number of messages in a deque and dispatch events to subscribers.
import { SocketStore } from 'tarkjs'
const socket = new SocketStore('ws://somesocket/', {
transformMessage: (data) => JSON.parse(data),
capacity: 10,
socketName: 'somesocket'
})
socket.subscribe((e) => {
console.log(e.payload.data)
})
socket.onOpen = () => socket.send(JSON.stringify({payload: 'Hello socket'}))
socket.start()