TodoMVC 教程

To demonstrate the Flux architecture with some example code, let’s take on the classic TodoMVC application. The entire application is available in the React GitHub repo within the flux-todomvc example directory, but let’s walk through the development of it a step at a time.

To begin, we’ll need some boilerplate and get up and running with a module system. Node’s module system, based on CommonJS, will fit the bill very nicely and we can build off of react-boilerplate to get up and running quickly. Assuming you have npm installed, simply clone the react-boilerplate code from GitHub, and navigate into the resulting directory in Terminal (or whatever CLI application you like). Next run the npm scripts to get up and running: npm install, then npm run build, and lastly npm start to continuously build using Browserify.

The TodoMVC example has all this built into it as well, but if you’re starting with react-boilerplate make sure you edit your package.json file to match the file structure and dependencies described in the TodoMVC example’s package.json, or else your code won’t match up with the explanations below.

Source Code Structure

The index.html file may be used as the entry point into our app which loads the resulting bundle.js file, but we’ll put most of our code in a ‘js’ directory. Let’s let Browserify do its thing, and now we’ll open a new tab in Terminal (or a GUI file browser) to look at the directory. It should look something like this:

  1. myapp
  2. |
  3. + ...
  4. + js
  5. |
  6. + app.js
  7. + bundle.js // generated by Browserify whenever we make changes.
  8. + index.html
  9. + ...

Next we’ll dive into the js directory, and layout our application’s primary directory structure:

  1. myapp
  2. |
  3. + ...
  4. + js
  5. |
  6. + actions
  7. + components // all React components, both views and controller-views
  8. + constants
  9. + dispatcher
  10. + stores
  11. + app.js
  12. + bundle.js
  13. + index.html
  14. + ...

Creating a Dispatcher

Now we are ready to create a dispatcher. The same dispatcher that Facebook uses in production is available through npm, Bower, or GitHub. It provides you with a default implementation, Dispatcher. All we need to do is to instantiate the Dispatcher and export it as a singleton:

  1. var Dispatcher = require('flux').Dispatcher;
  2. module.exports = new Dispatcher();

The public API of the dispatcher consists of two main methods: register() and dispatch(). We’ll use register() within our stores to register each store’s callback. We’ll use dispatch() within our actions to trigger the invocation of the callbacks.

Creating Stores

A store updates itself in response to some action, and should emit a change event when done with it. We thus can use Node’s EventEmitter to get started with a store: we will use EventEmitter to broadcast the ‘change’ event to our controller-views so that they can re-render, if needed. So let’s take a look at what that looks like. I’ve omitted some of the code for the sake of brevity, but for the full version see TodoStore.js in the TodoMVC example code.

  1. var AppDispatcher = require('../dispatcher/AppDispatcher');
  2. var EventEmitter = require('events').EventEmitter;
  3. var TodoConstants = require('../constants/TodoConstants');
  4. var assign = require('object-assign');
  5. var CHANGE_EVENT = 'change';
  6. var _todos = {}; // collection of todo items
  7. /**
  8. * Create a TODO item.
  9. * @param {string} text The content of the TODO
  10. */
  11. function create(text) {
  12. // Using the current timestamp in place of a real id.
  13. var id = Date.now();
  14. _todos[id] = {
  15. id: id,
  16. complete: false,
  17. text: text
  18. };
  19. }
  20. /**
  21. * Delete a TODO item.
  22. * @param {string} id
  23. */
  24. function destroy(id) {
  25. delete _todos[id];
  26. }
  27. var TodoStore = assign({}, EventEmitter.prototype, {
  28. /**
  29. * Get the entire collection of TODOs.
  30. * @return {object}
  31. */
  32. getAll: function() {
  33. return _todos;
  34. },
  35. emitChange: function() {
  36. this.emit(CHANGE_EVENT);
  37. },
  38. /**
  39. * Controller-views will use this to listen for any changes on the store and,
  40. * maybe, re-render themselves.
  41. * @param {function} callback
  42. */
  43. addChangeListener: function(callback) {
  44. this.on(CHANGE_EVENT, callback);
  45. },
  46. /**
  47. * Controller-views will use this to stop listening to the store.
  48. * @param {function} callback
  49. */
  50. removeChangeListener: function(callback) {
  51. this.removeListener(CHANGE_EVENT, callback);
  52. }
  53. });
  54. // Register a callback to handle all updates.
  55. AppDispatcher.register(function(action) {
  56. var text;
  57. switch(action.actionType) {
  58. case TodoConstants.TODO_CREATE:
  59. text = action.text.trim();
  60. if (text !== '') {
  61. create(text);
  62. }
  63. TodoStore.emitChange();
  64. break;
  65. case TodoConstants.TODO_DESTROY:
  66. destroy(action.id);
  67. TodoStore.emitChange();
  68. break;
  69. // add more cases for other actionTypes, like TODO_UPDATE, etc.
  70. default:
  71. // no op
  72. }
  73. })
  74. module.exports = TodoStore;

There are a few important things to note in the above code. To start, we are maintaining a private data structure called _todos. This object contains all the individual to-do items. Because this variable lives outside the class, but within the closure of the module, it remains private — it cannot be directly changed from outside of the module. This helps us preserve a distinct input/output interface for the flow of data by making it impossible to update the store without using an action.

Another important part is the registration of the store’s callback with the dispatcher. The callback function currently only handles two actionTypes, but later we can add as many as we need.

Listening to Changes with a Controller-View

We need a React component near the top of our component hierarchy to listen for changes in the store. In a larger app, we would have more of these listening components, perhaps one for every section of the page. In Facebook’s Ads Creation Tool, we have many of these controller-like views, each governing a specific section of the UI. In the Lookback Video Editor, we only had two: one for the animated preview and one for the image selection interface. Here’s one for our TodoMVC example. Again, this is slightly abbreviated, but for the full code you can take a look at the TodoMVC example’s TodoApp.react.js

  1. var Footer = require('./Footer.react');
  2. var Header = require('./Header.react');
  3. var MainSection = require('./MainSection.react');
  4. var React = require('react');
  5. var TodoStore = require('../stores/TodoStore');
  6. /**
  7. * Retrieve the current TODO data from the TodoStore.
  8. */
  9. function getTodoState() {
  10. return {
  11. allTodos: TodoStore.getAll()
  12. };
  13. }
  14. var TodoApp = React.createClass({
  15. getInitialState: function() {
  16. return getTodoState();
  17. },
  18. componentDidMount: function() {
  19. TodoStore.addChangeListener(this._onChange);
  20. },
  21. componentWillUnmount: function() {
  22. TodoStore.removeChangeListener(this._onChange);
  23. },
  24. /**
  25. * @return {object}
  26. */
  27. render: function() {
  28. return (
  29. <div>
  30. <Header />
  31. <MainSection
  32. allTodos={this.state.allTodos}
  33. />
  34. <Footer allTodos={this.state.allTodos} />
  35. </div>
  36. );
  37. },
  38. _onChange: function() {
  39. this.setState(getTodoState());
  40. }
  41. });
  42. module.exports = TodoApp;

Now we’re in our familiar React territory, utilizing React’s lifecycle methods. We set up the initial state of this controller-view in getInitialState(), register an event listener in componentDidMount(), and then clean up after ourselves within componentWillUnmount(). We render a containing div and pass down the collection of states we got from the TodoStore.

The Header component contains the primary text input for the application, but it does not need to know the state of the store. The MainSection and Footer do need this data, so we pass it down to them.

More Views

At a high level, the React component hierarchy of the app looks like this:

  1. <TodoApp>
  2. <Header>
  3. <TodoTextInput />
  4. </Header>
  5. <MainSection>
  6. <ul>
  7. <TodoItem />
  8. </ul>
  9. </MainSection>
  10. </TodoApp>

If a TodoItem is in edit mode, it will also render a TodoTextInput as a child. Let’s take a look at how some of these components display the data they receive as props, and how they communicate through actions with the dispatcher.

The MainSection needs to iterate over the collection of to-do items it received from TodoApp to create the list of TodoItems. In the component’s render() method, we can do that iteration like so:

  1. var allTodos = this.props.allTodos;
  2. for (var key in allTodos) {
  3. todos.push(<TodoItem key={key} todo={allTodos[key]} />);
  4. }
  5. return (
  6. <section id="main">
  7. <ul id="todo-list">{todos}</ul>
  8. </section>
  9. );

Now each TodoItem can display its own text, and perform actions utilizing its own ID. Explaining all the different actions that a TodoItem can invoke in the TodoMVC example goes beyond the scope of this article, but let’s just take a look at the action that deletes one of the to-do items. Here is an abbreviated version of the TodoItem:

  1. var React = require('react');
  2. var ReactPropTypes = React.PropTypes;
  3. var TodoActions = require('../actions/TodoActions');
  4. var TodoTextInput = require('./TodoTextInput.react');
  5. var TodoItem = React.createClass({
  6. propTypes: {
  7. todo: ReactPropTypes.object.isRequired
  8. },
  9. render: function() {
  10. var todo = this.props.todo;
  11. return (
  12. <li
  13. key={todo.id}>
  14. <label>
  15. {todo.text}
  16. </label>
  17. <button className="destroy" onClick={this._onDestroyClick} />
  18. </li>
  19. );
  20. },
  21. _onDestroyClick: function() {
  22. TodoActions.destroy(this.props.todo.id);
  23. }
  24. });
  25. module.exports = TodoItem;

With a destroy action available in our library of TodoActions, and a store ready to handle it, connecting the user’s interaction with application state changes could not be simpler. We just wrap our onClick handler around the destroy action, provide it with the id, and we’re done. Now the user can click the destroy button and kick off the Flux cycle to update the rest of the application.

Text input, on the other hand, is just a bit more complicated because we need to hang on to the state of the text input within the React component itself. Let’s take a look at how TodoTextInput works.

As you’ll see below, with every change to the input, React expects us to update the state of the component. So when we are finally ready to save the text inside the input, we will put the value held in the component’s state in the action’s payload. This is UI state, rather than application state, and keeping that distinction in mind is a good guide for where state should live. All application state should live in the store, while components occasionally hold on to UI state. Ideally, React components preserve as little state as possible.

Because TodoTextInput is being used in multiple places within our application, with different behaviors, we’ll need to pass the onSave method in as a prop from the component’s parent. This allows onSave to invoke different actions depending on where it is used.

  1. var React = require('react');
  2. var ReactPropTypes = React.PropTypes;
  3. var ENTER_KEY_CODE = 13;
  4. var TodoTextInput = React.createClass({
  5. propTypes: {
  6. className: ReactPropTypes.string,
  7. id: ReactPropTypes.string,
  8. placeholder: ReactPropTypes.string,
  9. onSave: ReactPropTypes.func.isRequired,
  10. value: ReactPropTypes.string
  11. },
  12. getInitialState: function() {
  13. return {
  14. value: this.props.value || ''
  15. };
  16. },
  17. /**
  18. * @return {object}
  19. */
  20. render: function() /*object*/ {
  21. return (
  22. <input
  23. className={this.props.className}
  24. id={this.props.id}
  25. placeholder={this.props.placeholder}
  26. onBlur={this._save}
  27. onChange={this._onChange}
  28. onKeyDown={this._onKeyDown}
  29. value={this.state.value}
  30. autoFocus={true}
  31. />
  32. );
  33. },
  34. /**
  35. * Invokes the callback passed in as onSave, allowing this component to be
  36. * used in different ways.
  37. */
  38. _save: function() {
  39. this.props.onSave(this.state.value);
  40. this.setState({
  41. value: ''
  42. });
  43. },
  44. /**
  45. * @param {object} event
  46. */
  47. _onChange: function(/*object*/ event) {
  48. this.setState({
  49. value: event.target.value
  50. });
  51. },
  52. /**
  53. * @param {object} event
  54. */
  55. _onKeyDown: function(event) {
  56. if (event.keyCode === ENTER_KEY_CODE) {
  57. this._save();
  58. }
  59. }
  60. });
  61. module.exports = TodoTextInput;

The Header passes in the onSave method as a prop to allow the TodoTextInput to create new to-do items:

  1. var React = require('react');
  2. var TodoActions = require('../actions/TodoActions');
  3. var TodoTextInput = require('./TodoTextInput.react');
  4. var Header = React.createClass({
  5. /**
  6. * @return {object}
  7. */
  8. render: function() {
  9. return (
  10. <header id="header">
  11. <h1>todos</h1>
  12. <TodoTextInput
  13. id="new-todo"
  14. placeholder="What needs to be done?"
  15. onSave={this._onSave}
  16. />
  17. </header>
  18. );
  19. },
  20. /**
  21. * Event handler called within TodoTextInput.
  22. * Defining this here allows TodoTextInput to be used in multiple places
  23. * in different ways.
  24. * @param {string} text
  25. */
  26. _onSave: function(text) {
  27. TodoActions.create(text);
  28. }
  29. });
  30. module.exports = Header;

In a different context, such as in editing mode for an existing to-do item, we might pass an onSave callback that invokes TodoActions.update(text) instead.

Creating Semantic Actions

Here is the basic code for the two actions we used above in our views:

  1. /**
  2. * TodoActions
  3. */
  4. var AppDispatcher = require('../dispatcher/AppDispatcher');
  5. var TodoConstants = require('../constants/TodoConstants');
  6. var TodoActions = {
  7. /**
  8. * @param {string} text
  9. */
  10. create: function(text) {
  11. AppDispatcher.dispatch({
  12. actionType: TodoConstants.TODO_CREATE,
  13. text: text
  14. });
  15. },
  16. /**
  17. * @param {string} id
  18. */
  19. destroy: function(id) {
  20. AppDispatcher.dispatch({
  21. actionType: TodoConstants.TODO_DESTROY,
  22. id: id
  23. });
  24. },
  25. };
  26. module.exports = TodoActions;

When the user creates a new to-do item, the payload produced by the TodoActions.create() will look like:

  1. {
  2. actionType: 'TODO_CREATE',
  3. text: 'Write blog post about Flux'
  4. }

Let’s wrap it up. When the user validates the text input in the Header component, TodoActions.create is called with the text for the new-todo. A new action is created, with a payload containing both the text and the action type. This action is dispatched to the stores which registered to the dispatcher, through a callback mechanism. In response to the dispatched action, the TodoStore updates itself by creating a new todo-item, then emits a ‘change’ event. The controller-view TodoApp, which is the root React component in this application, is listening for such events broadcasted by the store. It responds to the ‘change’ event by fetching the new collection of to-do items from the TodoStore and changes its state. React kicks in: this change in state automatically causes the TodoApp component to call its own render() method, and the render() method of all of its owned components. Any relevant, required updates to the DOM are performed by React at the end of this unidirectional “Flux chain”.

Start Me Up

The TodoApp component has still to be created. The bootstrap file of our application will be app.js. It simply takes the TodoApp component and renders it in the root element of the application.

  1. var React = require('react');
  2. var TodoApp = require('./components/TodoApp.react');
  3. React.render(
  4. <TodoApp />,
  5. document.getElementById('todoapp')
  6. );

Adding Dependency Management to the Dispatcher

As I said previously, our Dispatcher implementation is a bit naive. It’s pretty good, but it will not suffice for most applications. We need a way to be able to manage dependencies between Stores. Let’s add that functionality with a waitFor() method within the main body of the Dispatcher class.

We’ll need another public method, waitFor(). Note that it returns a Promise that can in turn be returned from the Store callback.

  1. /**
  2. * @param {array} promiseIndexes
  3. * @param {function} callback
  4. */
  5. waitFor: function(promiseIndexes, callback) {
  6. var selectedPromises = promiseIndexes.map(function(index) {
  7. return _promises[index];
  8. });
  9. return Promise.all(selectedPromises).then(callback);
  10. }

Now within the TodoStore callback we can explicitly wait for any dependencies to first update before moving forward. However, if Store A waits for Store B, and B waits for A, then a circular dependency will occur. A more robust dispatcher is required to flag this scenario with warnings in the console.

The Future of Flux

A lot of people ask if Facebook will release Flux as an open source framework. Really, Flux is just an architecture, not a framework, but we have released flux/utils which is a small set of utilities we use at Facebook to build Flux applications. There are also many other great frameworks out there that enable the Flux architecture.

Thanks for taking the time to read about how we build client-side applications at Facebook. We hope Flux proves as useful to you as it has to us.