Created
May 11, 2015 04:47
-
-
Save goatslacker/191bddd8d29117bc572f to your computer and use it in GitHub Desktop.
observe specific actions
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 Alt from './' | |
import { ACTION_KEY } from './lib/symbols/symbols' | |
const alt = new Alt() | |
alt.observe = function (action) { | |
const chain = [] | |
const subscriptions = [] | |
this.dispatcher.register((payload) => { | |
if (payload.action !== action[ACTION_KEY]) return | |
const state = chain.reduce((state, f) => { | |
const value = f(state) | |
return state === null ? state : value | |
}, payload.data) | |
if (state !== null) { | |
subscriptions.forEach(subscription => subscription(state)) | |
} | |
}) | |
return { | |
map(f) { | |
chain.push(f) | |
return this | |
}, | |
filter(f) { | |
chain.push((x) => { | |
const v = f(x) | |
return v ? x : null | |
}) | |
return this | |
}, | |
reduce(f, acc) { | |
chain.push(x => f(acc, x)) | |
return this | |
}, | |
subscribe(onChange) { | |
subscriptions.push(onChange) | |
const dispose = () => { | |
const id = subscriptions.indexOf(onChange) | |
if (id >= 0) subscriptions.splice(id, 1) | |
} | |
return { dispose } | |
} | |
} | |
} | |
const { fire } = alt.generateActions('fire') | |
const listen = alt.observe(fire).map((data) => { | |
return data * 2 | |
}) | |
.filter(x => x !== 12) | |
.reduce((state, nextState) => { | |
return state + nextState | |
}, 87) | |
const subscription = listen.subscribe(x => console.log('CHANGED', x)) | |
fire(12) | |
fire(6) | |
fire(3) | |
subscription.dispose() | |
fire(11) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment