Last active
August 29, 2015 14:20
-
-
Save goatslacker/e3509a364a067a679f87 to your computer and use it in GitHub Desktop.
stateless stores with reduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Dispatcher } from 'flux' | |
function isPromise(obj) { | |
return obj && (typeof obj === 'object' || typeof obj === 'function') && | |
typeof obj.then === 'function' | |
} | |
// the minimalest | |
class Alt { | |
constructor() { | |
this.dispatcher = new Dispatcher() | |
} | |
createActions(model) { | |
return Object.keys(model).reduce((actions, name) => { | |
const action = (...args) => { | |
const data = model[name](...args) | |
if (isPromise(data)) { | |
data | |
.then(x => this.dispatcher.dispatch({ action, data: x })) | |
.catch(e => this.dispatcher.dispatch({ action: null, data: e })) | |
} else { | |
this.dispatcher.dispatch({ action, data }) | |
} | |
} | |
actions[name] = action | |
return actions | |
}, {}) | |
} | |
createStore(reducer, initialState, ...args) { | |
const subscriptions = [] | |
let state = initialState | |
// dispatch event | |
this.dispatcher.register((payload) => { | |
state = reducer(state, payload, ...args) | |
subscriptions.forEach(f => f(state)) | |
}) | |
// our store | |
return { | |
subscribe(onChange) { | |
const id = subscriptions.push(onChange) | |
return () => subscriptions.splice(id, 1) | |
} | |
} | |
} | |
} | |
import assign from 'object-assign' | |
const alt = new Alt() | |
const actions = alt.createActions({ | |
fire(x) { | |
return x | |
} | |
}) | |
const store = alt.createStore((state, { action, data, meta }) => { | |
return assign({}, state, { | |
b: data | |
}) | |
}, { | |
a: 1, | |
b: 2 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment