Skip to content

Instantly share code, notes, and snippets.

@emadb emadb/Dispatcher.js
Last active Oct 10, 2017

Embed
What would you like to do?
medium - react and redux
const dispatcher = {
subscribers: [],
register(subscriber) {
this.subscribers.push(subscriber)
},
dispatch(action) {
this.subscribers.forEach(s => s(action))
}
}
class MyCounter extends React.Component {
constructor() {
super()
this.state = { counter: 0 }
}
plusOne() {
this.setState({counter: this.state.counter + 1})
}
render() {
return (
<div>
<div>Click count: {this.state.counter}</div>
<button onClick={this.plusOne.bind(this)}>Add 1</button>
</div>
)
}
}
class WithState extends React.Component {
constructor() {
super()
this.state = { counter: 0 }
}
plusOne() {
this.setState({counter: this.state.counter + 1})
}
render() {
return (
<MyCounter value={this.state.counter} onPlusOne={this.plusOne.bind(this)} />
)
}
}
class MyCounter extends React.Component {
render() {
return (
<div>
<div>Click count: {this.props.value}</div>
<button onClick={this.props.onPlusOne}>Add 1</button>
</div>)
}
}
function MyCounter({value, onPlusOne}) {
return (
<div>
<div>Click count: {value}</div>
<button onClick={onPlusOne}>Add 1</button>
</div>)
}
function counterReducer(state, action) {
return {counter: state.counter + action.value}
}
function createWithState(WrappedComponent, reducer, INITIAL_STATE) {
return class WithState extends React.Component {
constructor() {
super()
this.state = INITIAL_STATE
}
componentWillMount() {
dispatcher.register(action => {
const nextState = reducer(this.state, action)
this.setState(nextState)
})
}
render() {
return (
<WrappedComponent {...this.state} />
)
}
}
}
function MyCounter({counter}) {
return (
<div>
<div>Click count: {counter}</div>
<button onClick={() => dispatcher.dispatch({value: 1})}>Add 1</button>
</div>)
}
const MyComponent = createWithState(MyCounter, counterReducer, {counter: 0})
function counterReducer(state, action) {
return {counter: state.counter + action.value}
}
class WithState extends React.Component {
constructor() {
super()
this.state = { counter: 0 }
}
componentWillMount() {
dispatcher.register(action => {
const nextState = counterReducer(this.state, action)
this.setState(nextState)
})
}
render() {
return (
<MyCounter value={this.state.counter} />
)
}
}
function MyCounter({value, onPlusOne}) {
return (
<div>
<div>Click count: {value}</div>
<button onClick={() => dispatcher.dispatch({value: 1})}>Add 1</button>
</div>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.