Skip to content

Instantly share code, notes, and snippets.

@goatslacker
Created May 13, 2015 05:46
Show Gist options
  • Save goatslacker/619c6d8d006977ff49e9 to your computer and use it in GitHub Desktop.
Save goatslacker/619c6d8d006977ff49e9 to your computer and use it in GitHub Desktop.
Malt - A minimal alt
import { Dispatcher } from 'flux'
import transmitter from 'transmitter'
class Alt {
constructor() {
this.dispatcher = new Dispatcher()
}
createActions(model) {
return Object.keys(model).reduce((actions, name) => {
const action = (...args) => {
const data = model[name](...args)
this.dispatcher.dispatch({ action, data })
}
actions[name] = action
return actions
}, {})
}
createStore(model) {
let state = model.state
const bus = transmitter()
const observables = model.observe(this, state)
const dispatchToken = this.dispatcher.register((payload) => {
const signals = Object.keys(observables).reduce((obj, key) => {
if (observables[key] === payload.action) obj[key] = payload.data
return obj
}, {})
state = model.reduce(this, state, signals)
const output = model.output(this, state)
bus.push(output)
})
return {
dispatchToken,
subscribe: bus.subscribe
}
}
registerActions(actions) {
Object.keys(actions).forEach((name) => {
this[name] = this.createActions(actions[name])
})
}
registerStores(stores) {
Object.keys(stores).forEach((name) => {
this[name] = this.createStore(stores[name])
})
}
}
function id() {
return Math.random().toString(36).substr(2, 7)
}
const TodoActions = {
addTodo(text) {
return { id: id(), text }
}
}
const TodoStore = {
state: {},
observe(context, state) {
return {
todo: context.TodoActions.addTodo
}
},
reduce(context, state, signals) {
const { todo } = signals
state[todo.id] = todo
return state
},
output(context, state) {
return state
}
}
class Flux extends Alt {
constructor() {
super()
this.registerActions({ TodoActions })
this.registerStores({ TodoStore })
}
}
function test() {
const { TodoActions, TodoStore } = new Flux()
const { dispose } = TodoStore.subscribe(state => console.log('NEW TODOS', state))
TodoActions.addTodo('hello world')
TodoActions.addTodo('whats up')
dispose()
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment