Skip to content

JS Guide Section: Dispatcher events #3

@OscarGodson

Description

@OscarGodson

There's a lot of free-form strings in the dispatching system, Flux. For example, let's look at this code:

app-dispatcher.js

var AppDispatcher = assign(new Dispatcher(), {
  handlePageAction: function(action) {
    this.dispatch({
      source: 'PAGE_ACTION',
      action: action
    });
  }
});

page-actions.js

var PageActions = {
  updateTitle: function (text) {
    AppDispatcher.handlePageAction({
      type: 'titleUpdate',
      text: text
    });
  }
};

There's four important pieces here:

  1. source in dispatch()
  2. action in dispatch()
  3. type in handlePageAction
  4. text in handlePageAction

The source attribute is meant to give the category of dispatched events. In the example above, its PAGE_ACTION. All events dispatched from here are page related actions (such as updating the page title, description, etc). It is capitalized and underscore. (This is just React convention I guess ¯_(ツ)_/¯)

The action is all the data you want given to anything that registers with this dispatcher. This is passed in from the page-actions component.

type is the type of source event that is happening. It's camelcased to match methods. This way you can write code like below that can easily call an event on the component registering with it.:

AppDispatcher.register(function(payload) {
  if (payload.source == 'PAGE_ACTION') {
    self[payload.action.type](payload.action.text);
  }
});

In Action components like page-actions you only have to pass a type, but otherwise you can pass any data you want. text is an example of that. text itself isn't important, just the fact you can pass any data you might need to pass along here.

It's usually recommended, however, if you can, try to use the same naming scheme when adding more methods to an existing Actions component. For example, if every method passes in a data param to the dispatcher, don't use the keyword text instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions