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