Skip to content

Instantly share code, notes, and snippets.

@mitu217
Created February 15, 2017 17:35
Show Gist options
  • Save mitu217/d00a0ca28c5c644f6abbc85f8ae1e0c8 to your computer and use it in GitHub Desktop.
Save mitu217/d00a0ca28c5c644f6abbc85f8ae1e0c8 to your computer and use it in GitHub Desktop.
React + Fluxサンプルコード(動かないかも)
'use strict';
const Dispatcher = require('./Dispatcher');
class CounterActions extends Dispatcher.Actions {
submitClicked (text) {
this.emit('submit', text);
}
}
module.exports = new CounterActions();
'use strict';
const Dispatcher = require('./Dispatcher');
class CounterStore extends Dispatcher.Store {
init () {
this._initState();
Dispatcher.on('submit', (text) => {
this.setText(text);
this.emit('change');
});
}
getState () {
return this.state;
}
_initState () {
this.state = {
text: 'hello'
};
}
setText (text) {
this.state.text = text;
}
}
module.exports = new CounterStore();
/**
* A simple Flux implementation with EventEmitter.
* @author amagitakayosi <amagitakayosi@hatena.ne.jp>
* @license MIT License
*/
'use strict';
const EventEmitter = require('events').EventEmitter;
const Dispatcher = new EventEmitter();
Dispatcher.on('__DISPATCH__', (action) => {
Dispatcher.emit(action.type, action.payload);
});
// Define Actions class bound with Dispatcher
class Actions {
emit (actionType, payload) {
Dispatcher.emit('__DISPATCH__', {
type : actionType,
payload : payload,
});
}
}
class Store extends EventEmitter {
constructor () {
super();
this.state = {};
}
getState () {
return this.state;
}
}
Dispatcher.Actions = Actions;
Dispatcher.Store = Store;
module.exports = Dispatcher;
'use strict';
const React = require('react');
const CounterStore = require('./CounterStore');
const CounterActions = require('./CounterActions');
class MainComponent extends React.Component {
constructor (props) {
super(props);
this.state = CounterStore.getState();
}
componentDidMount () {
CounterStore.on('change', this.updateState.bind(this));
}
updateState () {
this.setState(CounterStore.getState());
}
render () {
return(
<div className="main">
<p>
<input
type="text"
ref="input" />
<input type="button" onClick={() => this.onSubmit()} value="apply" />
</p>
<p>{this.state.text}</p>
</div>
);
}
onSubmit () {
CounterActions.submitClicked(this.refs.input.value);
}
}
module.exports = Main;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment