Reflux Store in both a listener (both listening for action, but also to listen to the store) but it is also a publisher.
First, listening to an individual action
const Reflux = require('reflux'); const action = Reflux.createAction(); const store = Reflux.createStore({ init() { this.data = { num:0 }; // store监听action this.listenTo(action, function(){ this.data.num++; this.trigger(this.data); }.bind(this)) } }) // listens store trigger store.listen (the Data => console.log (the Data)); // trigger action action.trigger('in action'); action(); action(); action(); action(); action();
Note: 1. store.listen method to store itself trigger for monitoring.
2. store.listenTo listen to other objects can be monitored.
Second, while monitoring multiple actions
const Reflux = require('reflux'); // const actions = Reflux.createActions(['action1', 'action2']); const actions = Reflux.createActions({ action1: { asyncResult: true }, action2: { asyncResult: true } }); const store = Reflux.createStore({ listenables: actions, // init() { // this.listenToMany(actions) // }, action1 () { console.log('func in action1'); }, onAction1Completed () { console.log('action1 completed') }, onAction2() { console.log('func in action2') } }) actions.action1(); actions.action2(); actions.action1.completed();
Here, the attribute listenables createStore or use listenToMany in the init function can be implemented to monitor a plurality of action. With this wording corresponding to the callback function, the same name may be associated with each action, as action1; may also be used on + Action, such as onAction2. If asyncResult attribute definition action, following a default completed and failed two children.
Three, react with the binding Reflux {createAction Import Demo, createstore} from 'reflux' ;
import React from 'react'; const action = createAction(); const store = createStore({ init() { this.data = {num: 0}; this.listenTo(action, this.onClick); }, onClick () { this.data.num ++; this.trigger(this.data); } }) // React UI class ContainerUI extends React.Component { constructor (props) { super(props); this.state = { a: 0 } } componentDidMount () {
// Close function to generate the this .unmount = store.listen (Data => { the this .setState ({ Surely, data.num }) }) } componentWillUnmont () {
// call the function to close the this .unmount (); } render () { return ( <div> { this.state.num } <button onClick={action}>自增</button> </div> ) } } export default ContainerUI;