Home Reference Source Repository

tarkjs

Collection of promise oriented functions and classes.

travis-ci Test Coverage Code Climate esdocs npm version npm downloads Known Vulnerabilities Dependencies devDependencies Status MIT license

Installation

Install with npm: npm i -S tarkjs

Usage

ES6 imports.

import * as tarkjs from 'tarkjs'

There is no default export.

Custom Events and Stores

EventBus

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((value) => value.reduce((p,n) => p+n))
Regex handler

Give a regex as event to EventBus#addEventHandler to handle any events that match the pattern.

Notifiers
PromiseStore

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')
SocketStore

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()

Documentation

Full documentation