Skip to content

Instantly share code, notes, and snippets.

@camsong
Last active January 30, 2016 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camsong/aa7c134c14e3f126a5bb to your computer and use it in GitHub Desktop.
Save camsong/aa7c134c14e3f126a5bb to your computer and use it in GitHub Desktop.
function createStore(reducer, initialState) {
let currentState = initialState;
let listeners = [];
function subscribe(listener) {
listeners.push(listener);
const isSubscribed = true;
return function unsubscribe() {
if (!isSubscribed) return
isSubscribed = false
const index = listeners.indexOf(listener)
listeners.splice(index, 1)
}
}
function dispatch(action) {
currentState = reducer(state, action);
listeners.slice().forEach(listener => listener())
return action;
}
dispatch({ type: 'ACTION/@@INIT' })
return {
dispatch,
subscribe,
getState() {
return currentState;
}
};
}
class Provider extends React.Component {
static propTypes = {
store: storeShape.isRequired,
children: PropTypes.element.isRequired
};
static childContextTypes = {
store: storeShape.isRequired
};
getChildContext() {
return { store: this.store }
}
constructor(props, context) {
super(props, context)
this.store = props.store
}
render() {
let { children } = this.props;
return React.Children.only(children)
}
}
function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
return function wrapWithConnect(WrappedComponent) {
class Connect extends React.Component {
constructor(props, context) {
super(props, context)
this.store = props.store || context.store
const storeState = this.store.getState()
this.state = { storeState }
}
componentDidMount() {
this.trysubscribe()
}
componentWillUnmount() {
this.tryUnSubscribe()
}
trySubscribe() {
this.unsubscribe = this.store.subscribe(::this.handleChange)
this.handleChange()
}
tryUnsubscribe() {
this.unsubscribe()
this.unsubscribe = null
}
handleChange() {
const preivousState = this.store.storeState
const storeState = this.store.getState()
this.setState({ storeState })
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment