Last active
January 30, 2016 16:24
-
-
Save camsong/aa7c134c14e3f126a5bb to your computer and use it in GitHub Desktop.
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
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