Why do Flux architecture examples use constants for action types instead of strings?
Asked Answered
E

1

15

Throughout the examples and explanations of Flux architecture -- Facebook's counterpart to React -- action type names are referenced as enum constants rather than strings. (See examples at http://facebook.github.io/flux/) I am just looking for an articulation of why this is the preferred method.

I do not see a benefit in terms of authoring & convenience, because whether you type constants.actionTypes.UPDATE_DATA (enum constant) or 'UPDATE_DATA' (string), you have to know and type out the exact name. In fact, sometimes the use of non-strings adds complexity -- e.g. you can't as easily make an object with action types as keys and action handlers as values.

Are the benefits in organization, minification, or something else? I'm curious.

Exhaust answered 24/11, 2014 at 16:37 Comment(0)
H
22

You touched on it at the end of your question, but there are a couple benefits. Minification is an obvious one; another is the fact that static analysis tools can more easily find usages and catch errors.

Depending on your flux implementation, they can also help you catch typos. For example, in Fluxxor, if you try to bind a store handler to an action type of undefined, you'll get an exception; that means that passing c.UPDATE_DTA will throw, but passing 'UPDATE_DTA' will not.

Finally, they can help serve as documentation. If all the action types that your application generates are defined centrally as constants, it becomes easier to tell at-a-glance what kinds of operations the system as a whole responds to.

There's an ES6 feature that is available with Babel or Traceur (but not with the JSX transform at this time) that helps create object literals; the syntax is:

var handlers = {
  [const.UPDATE_DATA]: this.handleUpdateData,
  [const.OTHER_THING]: this.handleOtherThing
};
Hornstone answered 24/11, 2014 at 16:43 Comment(4)
Those were just the kind of details I was looking for. Great explanation.Exhaust
You can actually get pretty similar syntax in any javascript version by using a helper like this jsfiddle.net/ny7g09hcAcrimony
Upvote for the brilliant literal dotation of ES6. Btw, you can implement it using Babeljs also.Hyperpituitarism
I don't suppose you'll be able to minify them once they're exported (please correct me if I'm wrong).Tendon

© 2022 - 2024 — McMap. All rights reserved.