Skip to content

Instantly share code, notes, and snippets.

@eduard-tkv
Created April 19, 2017 20:58
Show Gist options
  • Save eduard-tkv/2968669658aa0a80a03260ceb5b7c2c9 to your computer and use it in GitHub Desktop.
Save eduard-tkv/2968669658aa0a80a03260ceb5b7c2c9 to your computer and use it in GitHub Desktop.
//actions/app-actions.js
import constants from '../constants/app-constants';
import dispatcher from '../dispatcher/dispatcher';
export let incrementActions = {
incrementCount: ()=>{
console.log('- inside incrementActions in app actions');
dispatcher.dispatch({
actionType: constants.INCREMENT
});
}
};
//dispatcher/dispatcher.js
import {Dispatcher} from 'flux';
const dispatcher = new Dispatcher();
export default dispatcher;
//stores/count-store.js
import constants from '../constants/app-constants';
import dispatcher from '../dispatcher/dispatcher';
import {EventEmitter} from 'events';
//Todo Backing Vars
let _count = 0;
function getCount(){
return _count;
}
function incrementCount(){
_count = _count + 1;
}
//Todo Define the actual actions
export let TodoStore = Object.assign({}, EventEmitter.prototype, {
getCount: getCount,
emitChange: function(){
this.emit('INCREMENT_EVENT');
},
addChangeListener: function(callback){
this.on('INCREMENT_EVENT', callback);
console.log('inside TodoStore.addChangeListener');
},
removeChangeListener: function(callback){
this.removeListener('INCREMENT_EVENT', callback);
console.log('listener removed');
}
});
//Register with the Dispatcher
dispatcher.register((action)=>{
console.log('- inside dispatcher register inside store');
switch(action.actionType){
case 'INCREMENT':
incrementCount();
TodoStore.emitChange();
break;
}
});
//src/index.js
import React from "react";
import ReactDOM from "react-dom";
import {incrementActions} from '../actions/app-actions';
import {TodoStore} from '../stores/count-store';
class App extends React.Component{
constructor(props){
super(props);
this.state = {
count: TodoStore.getCount()
};
this.increment = this.increment.bind(this);
this._onChange = this._onChange.bind(this);
}
componentDidMount(){
TodoStore.addChangeListener(this._onChange);
}
componentWillUnmount(){
TodoStore.removeChangeListener(this._onChange);
}
_onChange(){
console.log("_onChange fired inside index");
this.setState({
count: TodoStore.getCount()
});
}
increment(){
incrementActions.incrementCount();
}
render(){
return(
<div>
<h2>Click to increment</h2>
<p>{this.state.count}</p>
<button onClick={this.increment}>Click Here</button>
</div>
)
}
}
ReactDOM.render (
<App/>,
document.getElementById('container')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment