Skip to content

Instantly share code, notes, and snippets.

@madx
Last active December 16, 2020 08:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madx/d3a78ee726530a5e1bb0 to your computer and use it in GitHub Desktop.
Save madx/d3a78ee726530a5e1bb0 to your computer and use it in GitHub Desktop.
A simpler alternative to the Flux/Redux pattern http://drop.madx.me/1cldht84o9e5r79j4g1jwtl6niph9pp.gif

This is my proposal for a simpler implementation of the Flux pattern (well, like Redux, it is not exactly Flux)

(The name has nothing to do with ego, it's a joke from @Uhsac :))

export function createStore (initialState) {
let state = initialState
const observers = []
return {
dispatch (action, ...args) {
const oldState = state
state = action(state, ...args)
if (state === oldState) {
return
}
for (const observer of observers) {
observer(state, oldState)
}
},
subscribe (observer) {
observers.push(observer)
},
unsubscribe (observer) {
const index = observers.indexOf(observer)
if (index >= 0) {
observers.splice(index, 1)
}
}
}
}
/** @jsx element */
import {element, createApp} from 'deku'
import Immutable from 'immutable'
import {createStore} from './madux'
const initialState = Immutable.fromJS({
isOn: false
})
const actions = {
toggleOnOff (state) {
return state.set('isOn', !state.get('isOn'))
}
}
const App = {
render ({context, dispatch}) {
const isOn = context.get('isOn')
return (
<div>
<button onClick={() => dispatch(actions.toggleOnOff)}>
Click me!
</button>
<span>
{isOn ? 'On.' : 'Off.'}
</span>
</div>
)
}
}
const store = createStore(initialState)
const render = createApp(document.getElementById('app'), store.dispatch)
store.subscribe((state) => render(<App />, state))
store.dispatch((s) => s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment